Skip to main content
01

Second highest salary

EasysubqueriesaggregatesNULL

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

idnamesalary
1Noa100
2Avi200
3Dana300

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

sql
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:

sql
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:

  1. With duplicates (300, 300, 200) it returns 300. You need SELECT DISTINCT salary first.
  2. 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:

sql
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

  • RANK vs DENSE_RANK vs ROW_NUMBER: for 300, 300, 200 they give 1,1,3, 1,1,2 and 1,2,3.
  • An index on salary makes the MAX subquery a single index lookup.

Reference solution

sql
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);