To find the third highest salary in SQL Server, we can use similar approaches to those for finding the second highest salary, but adjusted to find the third highest.
Method 1: Using DISTINCT
with ORDER BY
and OFFSET-FETCH
This method finds the third distinct highest salary.The query sorts the salaries in descending order and skips the top two rows (OFFSET 2 ROWS
), then fetches the next row (FETCH NEXT 1 ROW
), giving you the third highest salary.
Method 2: Using the ROW_NUMBER()
Function
This method is effective when there are duplicates and you want to rank salaries.The ROW_NUMBER()
function assigns a unique rank to each salary in descending order, and you filter for the third rank.
Method 3: Using DENSE_RANK()
This method is helpful if there are ties (duplicate salaries) and you still want the third highest distinct value.The DENSE_RANK()
function is similar to ROW_NUMBER()
, but it assigns the same rank to equal (duplicate) values. This ensures that if there are ties, the correct rank is still returned.