Second highest salary
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Write a query that returns the second highest distinct salary in the employees table, in a column named second_highest_salary.
If there is no second highest salary (one employee, or everyone earns the same), return a single row with NULL.
Example
employees
| id | name | salary |
|---|---|---|
| 1 | Noa | 100 |
| 2 | Avi | 200 |
| 3 | Dana | 300 |
Result:
| second_highest_salary |
|---|
| 200 |
If the top salary is shared, say 300, 300, 200, the answer is 200, not 300.
Tip
The second highest salary is the highest one that is smaller than the highest one.
Schema
CREATE TABLE employees (
id INT PRIMARY KEY,
name TEXT NOT NULL,
salary INT NOT NULL
);Approach
Find the top salary with a subquery, then take the MAX of everything below it:
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);The NULL case comes for free: an aggregate like MAX over zero rows still returns one row, with NULL. That is why this beats the popular ORDER BY salary DESC LIMIT 1 OFFSET 1, which has two problems:
- With duplicates (
300, 300, 200) it returns300. You needSELECT DISTINCT salaryfirst. - When there is no second salary it returns zero rows, not a row with
NULL.
The window function version
Interviewers often ask you to generalize to the N-th highest salary. DENSE_RANK gives tied salaries the same rank with no gaps:
SELECT MAX(salary) AS second_highest_salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk = 2;Wrapping it in MAX again turns "no rows" into a NULL row.
Follow-ups
RANKvsDENSE_RANKvsROW_NUMBER: for300, 300, 200they give1,1,3,1,1,2and1,2,3.- An index on
salarymakes theMAXsubquery a single index lookup.
Reference solution
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);