Find Nth Highest Salary in SQL
Introduction
A typical SQL Server interview question is to locate the third wage in a database table of employees. The nth highest pay can be discovered in a variety of methods. All of the following questions will also have answers by the time this article is finished.
- How to use a subquery in SQL Server to discover the nth highest income
- Using a CTE, how to determine the nth highest salary in SQL Server
- Finding the second, third, or fifteenth highest wage
For this demonstration, let's utilize the following Employees table.
ID | FirstName | LastName | Gender | Salary |
1 | Ben | Hoskins | Male | 70000 |
2 | Mark | Hastings | Male | 60000 |
3 | Steve | Pound | Male | 45000 |
4 | Ben | Hoskins | Male | 70000 |
5 | Philip | Hastings | Male | 45000 |
6 | Mary | Lambeth | Female | 30000 |
7 | Valarie | Vikings | Female | 35000 |
8 | John | Stanmore | Male | 80000 |
Create table Employees |
It is simple to locate the greatest wage. Simply use the Max() method, as seen below. Select Max(Salary) from Employees Utilize a sub query combined with the Max() method as demonstrated below to obtain the second-highest income. Select Max(Salary) from Employees where Salary < (Select Max(Salary) from Employees)
Using a subquery, locate the nth highest income.
SELECT TOP 1 SALARY |
Utilizing CTE, determine the nth highest salary.
WITH RESULT AS |
Any of the searches listed above can be used to determine the second highest income. Simply substitute 2 for N. Similarly, simply substitute 3 for N to discover the third highest income.
Please Note: You may have noticed that the following query may be used to retrieve the nth highest income on several websites. Only if there are no duplicates will the following query be successful.
WITH RESULT AS |