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

No comments:

Post a Comment