DEV Community

stuxnat
stuxnat

Posted on

SQL 2ND Highest Salary

Here are several ways to find the second highest salary, given a table of employee salaries in SQL.

Example table:

employee table:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+

POSSIBLE SOLUTIONS:
SOLUTION 1:
SELECT MAX(salary) as SecondHighestSalary FROM employee WHERE salary NOT IN (SELECT MAX(salary) FROM employee);

SOLUTION 2:

SELECT * FROM employee
GROUP BY salary
ORDER BY salary DESC LIMIT 1,1;

SOLUTION 3:
SELECT DISTINCT salary AS SecondHighestSalary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1

Discussion (0)