Find Nth Highest Salary in SQL Server

"Find nth Highest Salary?" is a very common question being asked in interviews.

There are no. of ways to find the nth highest value from the table.

In this post, I am sharing some of the ways to find out the same.

Lets first create a Salary table and populate some data in it.
create table tblSalary (salary INT)
insert into tblSalary
select 5000 union all
select 5000 union all
select 9000 union all
select 8000 union all
select 7000 union all
select 7000 union all
select 8000 union all
select 3000

In the table, highest value is 9000 and 2nd highest value is 8000 which is duplicate so 3rd distinct highest value is 7000.

Now lets find out 3rd highest salary with different ways
declare @nHighest int
set @nHighest = 3 --Set value here to get nth highest value

-- Method 1
select  min(salary) as salary
from (
  select  distinct top (@nHighest) salary as salary
  from  tblSalary order by salary desc
) tab

-- Method 2
select  top 1 (salary)
from (
  select  distinct top (@nHighest) salary as salary
  from  tblSalary order by salary desc
) tab order by salary

-- Method 3
select  distinct (a.salary)
from    tblSalary a
where    @nHighest = (select count (distinct (b.salary))
from    tblSalary b where a.salary<=b.salary)

-- Method 4
select  distinct salary
from (
  select  dense_rank() over (order by salary desc) as rnk, salary
  from  tblSalary
) tab where rnk = @nHighest
OUTPUT

I am a Software Engineer and passionate programmer. Love working in SQL Server. Like participating in online technical communities like asp.net, MSDN, technical discussions and helping my friends, colleagues and others in their technical problems

Previous
Next Post »

3 comments

comments
Anonymous
June 13, 2012 at 6:32 PM delete

SELECT DISTINCT (A.SALARY)
FROM @TAB A
WHERE @nHighest = (SELECT COUNT (DISTINCT (B.SALARY))
FROM @TAB B WHERE A.SALARY<=B.SALARY)

Reply
avatar
Joe
October 28, 2012 at 1:01 AM delete

Thanks Sandeep! Great post. This page also explains it very well:

http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/

Reply
avatar
January 24, 2013 at 12:36 PM delete

very well explained you can find more on this at
http://wininterview.blogspot.in/

Reply
avatar

.