Query to find 2nd largest value in a column in Table

Problem: Write a SQL query to find the 2nd largest value in a column in a table.

Examples:
In the 1st example find the 2nd largest value in column “Income” and in the 2nd one find the 2nd largest value in “Cost”.

Input: Table name- Employee
+------+--------+
| Name | Income |
+------+--------+
| abc  | 4000   |
| xyz  | 4752   |
| qwe  | 6579   |
+------+--------+

Output: 4752

Input: Table name- price_list
+-------------+--------+
| Item        | Cost   |
+-------------+--------+
| Apple       | 150    |
| Banana      | 175    |
| Mango       | 200    |
| Pineapple   | 180    |
+-------------+--------+

Output: 180 

Method-1:



Syntax:

SELECT MAX (column_name) 
FROM table_name 
WHERE column_name NOT IN (SELECT Max (column_name) 
                          FROM table_name); 

First we selected the max from that column in the table then we searched for the max value again in that column with excluding the max value which has already been found, so it results in the 2nd maximum value.

  • Example-1:
    SELECT MAX (Income) 
    FROM Employee 
    WHERE Salary NOT IN (SELECT Max (Income) 
                         FROM Employee); 
  • Example-2:
    SELECT MAX (Cost) 
    FROM price_list 
    WHERE Salary NOT IN (SELECT Max (Cost) 
                         FROM price_list); 

Method-2:

Syntax:

SELECT column_name
FROM table_name e
WHERE 2 = (SELECT COUNT (DISTINCT column_name) 
           FROM table_name p
           WHERE e.column_name<=p.column_name) 

This is a nested sub query which is a generic SQL query to print the Nth largest value in column. For each record processed by outer query, inner query will be executed and will return how many records has records has value less than the current value. If you are looking for second highest value then your query will stop as soon as inner query will return 2.

  • Example-1:
    SELECT Income
    FROM Employee e
    WHERE 2=(SELECT COUNT(DISTINCT Income) 
             FROM Employee p
             WHERE e.Income<=p.Income) 
  • Example-2:
    SELECT Cost
    FROM price_list e
    WHERE 2=(SELECT COUNT(DISTINCT Cost) 
             FROM price_list p
             WHERE e.Cost<=p.Cost) 


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.