BeginnerRanking

Second highest salary

Task

Return the second highest distinct salary from employees as a single column named second_highest. Two people share the top salary, so the answer is not the second row.

Row order does not matter. Column names do not have to match. SQLite dialect.

Tables

employees

id INTEGER, name TEXT, salary INTEGER

idnamesalary
1Asha120
2Ben120
3Chen110
4Dev95
5Eli110
Expected output
second_highest
110
Show solution
SQL
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

ROW_NUMBER and OFFSET count rows, not distinct values. DENSE_RANK or a nested MAX works on distinct values, and the MAX version returns NULL rather than no rows when there is no second salary.

The full explanation, with more examples, is in the question Second highest salary.