Find nth Highest Salary

To “Find nth Highest Salary?” is a very common question being asked in interviews. 

There are several ways to find the nth Highest value from the table. In this post, I am sharing some of the ways to find the same.

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

Way 1:

declare @nHighest int 
set @nHighest = 3 --Set value here to get nth highest value 
select  min(salary) 
from ( 
  select  distinct top (@nHighest) salary as salary 
  from  tblSalary order by salary desc 
) tab 

Way 2:

declare @nHighest int 
set @nHighest = 3 --Set value here to get nth highest value 
select  top 1 (salary) 
from ( 
  select  distinct top (@nHighest) salary as salary 
  from  tblSalary order by salary desc 
) tab order by salary 

Way 3 :

declare @nHighest int 
set @nHighest = 3 --Set value here to get nth highest value 
select  distinct (a.salary) 
from    tblSalary a 
where    @nHighest = (select count (distinct (b.salary)) 
from    tblSalary b where a.salary<=b.salary) 

Way 4:

declare @nHighest int 
set @nHighest = 3 --Set value here to get nth highest value 
select  distinct salary 
from ( 
  select  dense_rank() over (order by salary desc) as rnk, salary 
  from  tblSalary 
) tab where rnk = @nHighest
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s