Showing posts with label find nth highest salary in sql. Show all posts
Showing posts with label find nth highest salary in sql. Show all posts

Tuesday, February 3, 2015

Find Nth highest Salary without Using TOP and Max Keyword

For this we use Dense_Rank() Function

Now we will discuss how it works , and we will generate query for desired output step by step

There is a table Employee_Master which contain employee names and salary.

Now we will apply select query  and short it out in Descending order,This query will arrange the records in Descending order on the behalf of Salary.

select* from Employee_Master order by Salary desc




Now we are going to apply Dense_Rank() function, before applying this we need to understand that how it works ??

When we apply Dense_Rank() function it will create  one temporary  run time column which numbers the Salary according to the Rank priority like (1,2,3.....)

select Emp_Name,Salary,DENSE_RANK() over(order by Salary Desc)as RK from  Employee_Master

Now we can easily find the Nth highest salary from last query .

We will treat above last query as SUBQUERY and find out the Nth highest  salary with the help of Where Clause which will apply on Temporary Column(RK) like that-

If We want to find 3rd highest Salary-

select* from (select Emp_Name,Salary,DENSE_RANK() over(order by Salary Desc)as RK from  Employee_Master)as Employee_Master where RK=3

                                         
                                                      Author-Er. Rahul Kr. Yadav

Monday, February 2, 2015

How to get nth salary in sql

We are going to discuss very important Topic which usually asks in the Interviews.

We will create the required query step by step-

select * from Employee_Master



Firstly we need to specify what will be the output, for this we need to apply Desc order in select query, this query arrange all the records of  table in Descending Order on the Behalf of Salary.

select * from  Employee_Master order by Salary desc


Since We Need to find out Nth Highest salary(3rd),We will apply TOP keyword in last query.

select top(3) * from Employee_Master order by Salary desc



With the help of this output we can identify that what Should be the 3rd Highest salary .It will be 6000 which belongs to Employee Sagar, Because we have already selected Top 3 after applying Descending Order in select query.  



Now we need to  Generate query  for desired output.


We will use last query as Sub-Query and apply SELECT query on this subquery after that apply ASC order  and apply  TOP(1) on this query , it will generate desired output like that.

Select Top(1)* from (select top(3) * from Employee_Master order by Salary desc) as Employee_Master order by Salary asc


                                                   Author -Er. Rahul Kr. Yadav