25

How can I find the Nth highest salary in a table containing salaries in SQL Server?

0

11 Answers 11

35

You can use a Common Table Expression (CTE) to derive the answer.

Let's say you have the following salaries in the table Salaries:

 EmployeeID  Salary
--------------------
     10101   50,000
     90140   35,000
     90151   72,000
     18010   39,000
     92389   80,000

We will use:

DECLARE @N int
SET @N = 3  -- Change the value here to pick a different salary rank

SELECT Salary
FROM (
    SELECT row_number() OVER (ORDER BY Salary DESC) as SalaryRank, Salary
    FROM Salaries
) as SalaryCTE
WHERE SalaryRank = @N

This will create a row number for each row after it has been sorted by the Salary in descending order, then retrieve the third row (which contains the third-highest record).


For those of you who don't want a CTE (or are stuck in SQL 2000):

[Note: this performs noticably worse than the above example; running them side-by-side with an exceution plans shows a query cost of 36% for the CTE and 64% for the subquery]:

SELECT TOP 1 Salary
FROM 
(
    SELECT TOP N Salary
    FROM Salaries
    ORDER BY Salary DESC
) SalarySubquery
ORDER BY Salary ASC

where N is defined by you.

SalarySubquery is the alias I have given to the subquery, or the query that is in parentheses.

What the subquery does is it selects the top N salaries (we'll say 3 in this case), and orders them by the greatest salary.

If we want to see the third-highest salary, the subquery would return:

 Salary
-----------
80,000
72,000
50,000

The outer query then selects the first salary from the subquery, except we're sorting it ascending this time, which sorts from smallest to largest, so 50,000 would be the first record sorted ascending.

As you can see, 50,000 is indeed the third-highest salary in the example.

6
  • this part is unclear to me could u explain it to me SalarySubquery ORDER BY Salary ASC Oct 22, 2010 at 19:32
  • @NoviceToDotNet - I've edited my answer based on your comments -- I hope they clear things up. Oct 22, 2010 at 20:09
  • @LittleBobbyTables: I have edited ur answer - CTE part. If it's correct, kindly accept the changes, otherwise, correct me.
    – Viral Jain
    Sep 11, 2014 at 17:50
  • @ViralJain - and I rolled it back; the example I had works satisfactorily, and I don't see any reason for the changes. I'm dismayed to see the edit was approved by a bunch of robo-reviewers, but at least I have the small comfort that two people voted to reject the edit. Sep 11, 2014 at 19:04
  • @LittleBobbyTables: It indeed works perfectly as desired & needed by OP but CTE! You have mentioned CTE but it is not there in ur example - please correct my understanding of CTE or else see this link - technet.microsoft.com/en-us/library/ms190766(v=SQL.105).aspx
    – Viral Jain
    Sep 16, 2014 at 12:02
12

You could use row_number to pick a specific row. For example, the 42nd highest salary:

select  *
from    (
        select  row_number() over (order by Salary desc) as rn
        ,       *
        from    YourTable
        ) as Subquery
where   rn = 42

Windowed functions like row_number can only appear in select or order by clauses. The workaround is placing the row_number in a subquery.

5
select MIN(salary) from (
select top 5 salary from employees order by salary desc) x
1
  • So if there are only 4 salaries, you'll return the 4th highest? I would guess the expected answer is "null". Also, you need to use "distinct".
    – C S
    Feb 29, 2020 at 2:17
4
EmpID   Name    Salary
1   A   100
2   B   800
3   C   300
4   D   400
5   E   500
6   F   200
7   G   600

SELECT * FROM Employee E1
WHERE (N-1) = (
                SELECT COUNT(DISTINCT(E2.Salary))
                FROM Employee E2
                WHERE E2.Salary > E1.Salary
              )

Suppose you want to find 5th highest salary, which means there are total 4 employees who have salary greater than 5th highest employee. So for each row from the outer query check the total number of salaries which are greater than current salary. Outer query will work for 100 first and check for number of salaries greater than 100. It will be 6, do not match (5-1) = 6 where clause of outerquery. Then for 800, and check for number of salaries greater than 800, 4=0 false then work for 300 and finally there are totally 4 records in the table which are greater than 300. Therefore 4=4 will meet the where clause and will return 3 C 300.

2

try it...

use table_name
select MAX(salary)
from emp_salary
WHERE marks NOT IN (select MAX(marks)
from student_marks )
1
  • This will give 2nd highest but not nth highest
    – Tula
    Jun 9, 2021 at 15:37
1

Simple way WITHOUT using any special feature specific to Oracle, MySQL etc. Suppose in EMPLOYEE table Salaries can be repeated. Use query to find out rank of each ID.

select  *
from  (
select tout.sal, id, (select count(*) +1 from (select distinct(sal) distsal from     
EMPLOYEE ) where  distsal >tout.sal)  as rank  from EMPLOYEE tout
) result
order by rank

First we find out distinct salaries. Then we find out count of distinct salaries greater than each row. This is nothing but the rank of that id. For highest salary, this count will be zero. So '+1' is done to start rank from 1.

Now we can get IDs at Nth rank by adding where clause to above query.

select  *
from  (
select tout.sal, id, (select count(*) +1 from (select distinct(sal) distsal from     
EMPLOYEE ) where  distsal >tout.sal)  as rank  from EMPLOYEE tout
) result
where rank = N;
1

The easiest method is to get 2nd higest salary from table in SQL:

sql> select max(sal) from emp where sal not in (select max(sal) from emp);
1

Dont forget to use the distinct keyword:-

SELECT TOP 1 Salary
FROM 
(
    SELECT Distinct TOP N Salary
    FROM Salaries
    ORDER BY Salary DESC
) SalarySubquery
ORDER BY Salary ASC
1

Solution 1: This SQL to find the Nth highest salary should work in SQL Server, MySQL, DB2, Oracle, Teradata, and almost any other RDBMS: (note: low performance because of subquery)

SELECT * /*This is the outer query part */
FROM Employee Emp1
WHERE (N-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

The most important thing to understand in the query above is that the subquery is evaluated each and every time a row is processed by the outer query. In other words, the inner query can not be processed independently of the outer query since the inner query uses the Emp1 value as well.

In order to find the Nth highest salary, we just find the salary that has exactly N-1 salaries greater than itself.


Solution 2: Find the nth highest salary using the TOP keyword in SQL Server

SELECT TOP 1 Salary
FROM (
      SELECT DISTINCT TOP N Salary
      FROM Employee
      ORDER BY Salary DESC
      ) AS Emp
ORDER BY Salary

Solution 3: Find the nth highest salary in SQL Server without using TOP

SELECT Salary FROM Employee 
ORDER BY Salary DESC OFFSET N-1 ROW(S) 
FETCH FIRST ROW ONLY

Note that I haven’t personally tested the SQL above, and I believe that it will only work in SQL Server 2012 and up.

0
SELECT * FROM 
(select distinct postalcode  from Customers order by postalcode DESC)
limit 4,1;

4 here means leave first 4 and show the next 1.

Try this it works for me.

1
  • Postalcode here is column name and Customers is table name. Mar 7, 2018 at 13:27
-4

Very simple one query to find nth highest salary

SELECT DISTINCT(Sal) FROM emp ORDER BY Salary DESC LIMIT n,1
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.