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.
Find 2nd, 3rd or Nth Highest salary using LINQ
Create table Employees
(
ID int primary key identity,
FirstName nvarchar(50),
LastName nvarchar(50),
Gender nvarchar(50),
Salary int
)
GO
Insert into Employees values ('Sourabh', 'chauhan', 'Male', 70000)
Insert into Employees values ('Hemant', 'chauhan', 'Male', 60000)
Insert into Employees values ('Ravi', 'Thakur', 'Male', 45000)
Insert into Employees values ('Sourabh', 'Chauhan', 'Male', 70000)
Insert into Employees values ('Praveen', 'Yadav', 'Male', 45000)
Insert into Employees values ('Sanaya', 'sharma', 'Female', 30000)
Insert into Employees values ('Geetanjali', 'Mishra', 'Female', 35000)
Insert into Employees values ('Tom', 'Stanmore', 'Male', 80000)
GO
ID | FirstName | LastName | Gender | Salary |
1 | Sourabh | Chauhan | Male | 70000 |
2 | Hemant | Chauhan | Male | 60000 |
3 | Ravi | Thakur | Male | 45000 |
4 | Sourabh | chauhan | Male | 70000 |
5 | Praveen | Yadav | Male | 45000 |
6 | Sanaya | Sharma | Female | 30000 |
7 | Geetanjali | Mishra | Female | 35000 |
8 | Tom | Stanmore | Male | 80000 |
select top 1 salary from
(select distinct top N Salary from Employees order by Salary desc)
as result order by salary
--Relpace N with Any Number, you want to find the highest salary
2nd Method:-
select min(salary) from(
select distinct top N salary from employees order by salary desc) as sal
--Relpace N with Any Number, you want to find the highest salary
with cte as
(
select salary,DENSE_RANK() over (order by salary desc) as DenseRank from Employees
)
select top 1 salary from cte where DenseRank=N
--Relpace N with Any Number, you want to find the highest salary
For finding the Nth highest salary, we can use the above two queries
with CTE1 as(
select distinct salary,ROW_NUMBER() over (order by salary desc) as RowNumber
from Employees order by salary desc
)
select salary from CTE1 where RowNumber = N
--Relpace N with Any Number, you want to find the highest salary
Comments