How to find Nth highest salary from a table

17 Jan, 2022
Finding Nth highest salary in a table is the most common question asked in interviews. Here is a way to do this task using dense_rank() function. 
Consider the following table: Employee 
 
Query : 
select * from(
select ename, sal, dense_rank() 
over(order by sal desc)r from Employee) 
where r=&n;

To find to the 2nd highest sal set n = 2
To find 3rd highest sal set n = 3 and so on.
Output :  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
 
DENSE_RANK : 
DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1.This function accepts arguments as any numeric data type and returns NUMBER.As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause.In the above query the rank is returned based on sal of the employee table. In case of tie, it assigns equal rank to all the rows.  
DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER. The ranks are consecutive integers beginning with 1.
This function accepts arguments as any numeric data type and returns NUMBER.
As an analytic function, DENSE_RANK computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs in the order_by_clause.
In the above query the rank is returned based on sal of the employee table. In case of tie, it assigns equal rank to all the rows.  
Alternate Solution :—————————————————————————————————————————————————————————————————————– 
CREATE TABLE `Employee` ( 
`ENAME` varchar(225) COLLATE utf8_unicode_ci NOT NULL, 
`SAL` bigint(20) unsigned NOT NULL, 
PRIMARY KEY (`ENAME`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 
————————————————————————————————————————————————————- 
6th highest
mysql> select * from ((select * from Employee 
       ORDER BY `sal` DESC limit 6 ) AS T) 
       ORDER BY T.`sal` ASC limit 1;
Alternate use of Limit:
select * from Employee ORDER BY `sal` ASC limit 5,1; // will return 6th highest 


+-------+-----+
| ENAME | SAL |
+-------+-----+
| B     | 300 |
+-------+-----+
1 row in set (0.00 sec) 
——————————————————————————————————————————————————– 
mysql> select * from Employee;
+-------+-----+
| ENAME | SAL |
+-------+-----+
| A     | 100 |
| B     | 300 |
| C     | 200 |
| D     | 500 |
| F     | 400 |
| G     | 600 |
| H     | 700 |
| I     | 800 |
+-------+-----+
8 rows in set (0.00 sec) 
Thanks to Vijay for suggesting this alternate solution.  
Alternate Solution –Suppose the task is to find the employee with the Nth highest salary from the above table. We can do this as follows: 
Find the employees with top N distinct salaries.Find the lowest salary among the salaries fetched by the above query, this will give us the Nth highest salary.Find the details of the employee whose salary is the lowest salary fetched by the above query.
Find the employees with top N distinct salaries.
Find the lowest salary among the salaries fetched by the above query, this will give us the Nth highest salary.
Find the details of the employee whose salary is the lowest salary fetched by the above query.
Query:  
SELECT * FROM Employee WHERE sal = 
         (
            SELECT MIN(sal) FROM Employee 
            WHERE  sal IN (
                                 SELECT DISTINCT TOP N
                                     sal FROM Employee 
                                         ORDER BY sal DESC
                             )
        )
The above query will fetch the details of the employee with the Nth highest salary. Let us see how: 
Consider N = 4.
Starting with the most inner query, the query: “SELECT DISTINCT TOP 4 sal FROM Employee ORDER BY sal DESC” will produce the below result:  
51000
39800
35000
31500
The next outer query is: “SELECT MIN(sal) FROM Employee WHERE sal IN ( Result_Set_of_Previous_Query )“. This will return the below result:
31500
You can see that the above returned result is the required 4th highest salary.
Next is the most outer query, which is: “SELECT * FROM Employee WHERE sal = Result_of_Previous_Query“. This query will return the details of employees with 4th highest salary.  
________________________
ename             sal
________________________
  F        |     31500
           |
________________________
Another Solution –Here N = nth Highest Salary eg. 3rd Highest salary : N=3 .
SELECT ename,sal from Employee e1 where 
        N-1 = (SELECT COUNT(DISTINCT sal)from Employee e2 where e2.sal > e1.sal) 
Solution using Limit : 
    Select Salary from table_name order by Salary DESC limit n-1,1;
        Here we are ordering our salary in descending order so we will get highest salary first and then subsequently lower salaries. 
        Limit clause has two components, First component is to skip  number of rows from top and second component is display number of rows we want. 
   let us see with an example :
    To find 4th Highest salary query will be :
 Select Salary from table_name order by Salary DESC limit 3,1;
   Here  we are skipping 3 rows from Top and returning only 1 row after skipping .
 You can also find names of employees having Nth Highest Salary 
Select Emp_name from table_name where Salary =( Select Salary from table_name order by Salary DESC limit n-1,1);
There can be another question like find Nth Lowest Salary . In order to that , just reverse order using ASC ( if you don’t specify by default column will be ordered in ascending order).
 Select Salary from table_name order by Salary limit n-1,1;
16. Nth highest salary (Top 50 SQL Interview Questions) | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribers16. Nth highest salary (Top 50 SQL Interview Questions) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=orEkHRYo6jU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
&t=176s 
This article is contributed by Rishav Shandilya. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
real1107055
RohanPrajapati
rajgirisanket
unikam18
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
Difference between DDL and DML in DBMS
SQL Correlated Subqueries