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
| id | name | salary |
|---|---|---|
| 1 | Asha | 120 |
| 2 | Ben | 120 |
| 3 | Chen | 110 |
| 4 | Dev | 95 |
| 5 | Eli | 110 |
- Duplicates at the top mean ORDER BY … OFFSET 1 returns 120 again.
- Either take the MAX below the overall MAX, or use DENSE_RANK() and keep rank 2.
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.
Why this works
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.