Monday, September 16, 2013

How to find 2nd,3rd,4th ..... nth largest / smallest salary in a table

Hi All ,
   Just thought to share with you some simple SQL query that is used very frequently in our projects and mostly asked in interviews as well.
It is " Write a SQL Query to find the 2nd, 3rd, 4th ...........nth largest salary from a table".






Note  here N , N is equal to which largest salary you want to find. Like if you want to find 2nd highest , it will be Top 1 , if you want to find 3rd highest it will be Top 2 , if you want to find 4th highest it will be Top 3 and so on........

So Here is the SQL Query to find out the 3rd largest query from a table :



Similarly if you want to find the smallest salary , the above will remain same except you have to replace :
1)MAX(Salary) with MIN(Salary)  
2) Order by Salary Desc with Order by Salary Asc

Here's the query to find the 2nd smallest salary from the table ...




Thanks,
Nitin Sharma