HOW TO FIND Nth Highest Salary in SQL Server ?
This is one of the most common SQL Server interview questions that how to find the Nth highest salary of employee with their details?.
Where N could be any number for e.g. 1, 2,3, ..and so on
Lets create a employee table and insert some dummy records into a table.
CREATE TABLE Employee (EmpName varchar(10), salary int); INSERT INTO Employee VALUES ('Molly', 1000); INSERT INTO Employee VALUES ('Rozer', 2000); INSERT INTO Employee VALUES ('Jhonny', 3000); INSERT INTO Employee VALUES ('Williams', 4000); INSERT INTO Employee VALUES ('Ronaldo', 5000);
Nth Highest salary using Row_Number
Following statement uses Row_Number() function to get the 3rd highest salary.
SELECT EmpName , Salary FROM( SELECT ROW_NUMBER() OVER(ORDER BY Salary DESC) AS SNo , EmpName, Salary FROM Employee )Sal WHERE SNo = 3
As you can see, In employee table 3rd highest salary is 3000 and query returns the same value.
Nth Highest salary Using TOP Keyword
Following statement uses TOP keyword to get the 2nd highest salary.
SELECT TOP 1 * FROM (
SELECT TOP 2 EmpName , Salary FROM Employee ORDER BY Salary DESC
) Sal ORDER BY Salary ;
As you can see, In employee table 2nd highest salary is 4000 and query returns the same value.
10,023 total views, 1 views today