Find nth highest salary in SQL Server

In most of the interviews this question is asked,we have many ways to find the nth highest salary.

Suppose we have below data. And finding 3rd highest salary

Salary                                                           90000                                                     80000                                                     60000                                                     60000

Method 1 :

Select Top 1 salary from
(
Select distinct top 3 salary from employee
order by salary desc
) Result
order by salary

Output : 60000

Method 2 : 

With result as
(
Select salary,dense_rank() over (order by salary desc) drank from employee
)
Select salary from result
Where result.drank=3
Output : 6000

Method 3 : 

SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary
)

Leave a comment