SQL Query to find 2nd or 3rd or Nth highest salary. This is a very common SQL Server Interview Question. There are several ways of finding the 2nd or 3rd or Nth highest salary.
How to find nth highest salary in SQL Server using a Sub-Query
How to find nth highest salary in SQL Server using a CTE
selecttop1 salary from(selectdistincttop N Salary from Employees orderby Salary desc)as result orderby salary
--Relpace N with Any Number, you want to find the highest salary
SQL
2nd Method:-
2nd Method for finding Nth highest salary
selectmin(salary)from(selectdistincttop N salary from employees orderby salary desc)as sal
--Relpace N with Any Number, you want to find the highest salary
SQL
Find Nth highest salary using CTE and Dense_Rank()
Nth highest salary using CTE and DENSE_RANK()
with cte as(select salary,DENSE_RANK()over(orderby salary desc)as DenseRank from Employees
)selecttop1 salary from cte where DenseRank=N
--Relpace N with Any Number, you want to find the highest salary
SQL
For finding the Nth highest salary, we can use the above two queries
Find Nth highest salary using CTE and Row_Number()
Note:- The below query will only work if there are no duplicates. On Many websites, you have seen that the below query is used to find Nth highest salary. But it only works there are no duplicates
Nth Highest salary using ROW_NUMBER()
with CTE1 as(selectdistinct salary,ROW_NUMBER()over(orderby salary desc)as RowNumber
from Employees orderby salary desc)select salary from CTE1 where RowNumber = N
--Relpace N with Any Number, you want to find the highest salary
SQL
Note:- Replace N with any Number, You want to find the highest salary. For example , if you want to find 3rd highest salary, then replace N with 3.
Comments