JuniorCodingSQL
Write a query that returns the second highest salary
Try answering first
Model answer
The simplest portable query takes the maximum of everything below the maximum:
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
It compares distinct values, so two people at the top salary do not hide the second level. Because MAX without GROUP BY always returns one row, the result is NULL when there is no second salary, which is usually the behavior you want.
The window version generalizes to the Nth highest:
SELECT DISTINCT salary
FROM (
SELECT salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS rk
FROM employees
) t
WHERE rk = 2;
DENSE_RANK is the right function here, since RANK would skip a rank after ties and ROW_NUMBER would count duplicates. This version returns no row, not NULL, when the value does not exist.
LIMIT 1 OFFSET 1 is tempting but wrong when the top salary is duplicated, unless you add DISTINCT.
Key points
- MAX of values below the overall MAX works on any engine
- DENSE_RANK handles ties and generalizes to the Nth value
- The two versions differ when no second salary exists
Likely follow-ups
- How would you return the second highest salary per department?
Common mistakes
- Using LIMIT 1 OFFSET 1 without DISTINCT when salaries repeat
- Using ROW_NUMBER and counting duplicate salaries as separate levels