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.
SELECT MAX (Income)
FROM Employee
WHERE Income NOT IN (SELECT Max (Income)
FROM Employee);
SELECT MAX (Cost)
FROM price_list
WHERE Cost 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.
SELECT Income
FROM Employee e
WHERE 2=(SELECT COUNT(DISTINCT Income)
FROM Employee p
WHERE e.Income<=p.Income)
SELECT Cost
FROM price_list e
WHERE 2=(SELECT COUNT(DISTINCT Cost)
FROM price_list p
WHERE e.Cost<=p.Cost)