In this Tutorial, we will discuss, Multiple ways to Find 2nd, 3rd, and Nth Highest Salary in SQL. When it comes to SQL Server interviews, one of the most important questions is whether or not the candidate can write complex SQL queries.
Three ways to find the Nth Highest Salary in SQL
- Using Correlate subquery
- By using ROW_Number()
- TOP Keyword
- DENSE_RANK()
First, we need to create an Employee_salary table. The employee table has three columns, Id , Employeename, salary.
CREATE TABLE [dbo].[Employee_salary]( [id] [int] IDENTITY(1,1) NOT NULL, [Employeename] [varchar](10) NULL, [salary] [float] NULL )
Insert Employee data in the Employee table
INSERT INTO Employee_salary(Employeename,salary)VALUES('Ken','35000') INSERT INTO Employee_salary(Employeename,salary)VALUES('Wanida','60000') INSERT INTO Employee_salary(Employeename,salary)VALUES('Michael','55000') INSERT INTO Employee_salary(Employeename,salary)VALUES('Sariya','62000')
Retrieve the Employee Data
SELECT * FROM Employee_salary
Second Highest Salary in SQL
In the employee salary, we want to find out the second highest salary.
SELECT TOP 1 * FROM (SELECT TOP 2 salary FROM Employee_salary ORDER BY salary DESC) AS innerq ORDER BY salary
Also, check the Previous Article How to Find Top N records using SQL
First Highest Salary in SQL
In the employee salary, we want to find out the First highest salary.
SELECT TOP 1 * FROM (SELECT TOP 1 salary FROM Employee_salary ORDER BY salary DESC) AS innerq ORDER BY salary
Third highest Salary in SQL
In the employee salary, we want to find out the Third highest salary
SELECT TOP 1 * FROM (SELECT TOP 3 salary FROM Employee_salary ORDER BY salary DESC) AS innerq ORDER BY salary
Find the Nth Highest Salary Using DENSE_RANK
The DENSE_RANK function returns the rank of each row within a result set partition, with no gaps in the ranking values. The ranking in the DESNE_RANK() function is integer values starting from 1.
SELECT * FROM (SELECT Employeename,Salary,DENSE_RANK() over(ORDER BY salary desc) As nested_query FROM Employee_salary) AS nth_nestedquery WHERE nested_query=3
Find the Nth Highest Salary Using ROW_NUMBER
The ROW_NUMBER function is a window function that assigns a sequence integer to each row within the partition of a result set. Starting at 1 for the first row in each partition.
SELECT Employeename,Salary,ROW_NUMBER() over(ORDER BY salary desc) As NTH_nested_query FROM Employee_salary SELECT * FROM( SELECT Employeename,Salary,ROW_NUMBER() over(ORDER BY salary desc) As NTH_nested_query FROM Employee_salary) as NESTED_QUERY WHERE NTH_nested_query=3