IntermediateRanking

Return the Nth highest distinct salary, or NULL if there is none.

Scenario

An interview classic: return the 2nd highest salary. Two employees share the second-highest value, and the query must return NULL (not an empty result) when the Nth salary does not exist.

Interview answerTry answering first, then reveal

Rank the distinct values with DENSE_RANK() OVER (ORDER BY salary DESC) and pick rank N, or use SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET N-1. Wrap either in a scalar subquery: a scalar subquery with no rows returns NULL, which satisfies the "or NULL" part.

Explanation

"Distinct" is the key word. The salaries are 120, 110, 110, 95, 90 and 80, so the 2nd highest distinct salary is 110 and the 3rd is 95. DENSE_RANK gives exactly that numbering; RANK would number 95 as 4.

A query that finds nothing returns zero rows, not NULL. Selecting it as a scalar subquery (SELECT (subquery) AS nth) always returns exactly one row: the value, or NULL.

Per-group versions use PARTITION BY dept and filter on the rank.

Worked example

Run on DuckDB when this page was built; the results shown are the real output.

Sample data
SQL
CREATE TABLE employees (emp_id INT, name VARCHAR, dept VARCHAR, salary INT);
INSERT INTO employees VALUES
  (1, 'Asha', 'Engineering', 120), (2, 'Ben',  'Engineering', 110),
  (3, 'Chen', 'Engineering', 110), (4, 'Dev',  'Engineering',  90),
  (5, 'Eli',  'Sales',        95), (6, 'Fay',  'Sales',        80);

2nd, 3rd and 10th highest distinct salary

SQL
SELECT
  (SELECT DISTINCT salary FROM employees
   ORDER BY salary DESC LIMIT 1 OFFSET 1)                     AS second_highest,
  (SELECT salary FROM (SELECT salary,
            DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM employees) x
   WHERE r = 3 LIMIT 1)                                      AS third_highest,
  (SELECT DISTINCT salary FROM employees
   ORDER BY salary DESC LIMIT 1 OFFSET 9)                     AS tenth_highest;
Result
second_highestthird_highesttenth_highest
11095NULL

Second highest per department

SQL
SELECT dept, salary AS second_highest
FROM (SELECT DISTINCT dept, salary FROM employees) d
QUALIFY DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary DESC) = 2
ORDER BY dept;
Result
deptsecond_highest
Engineering110
Sales80

In production

  • Departments with a single distinct salary have no 2nd highest and simply do not appear in the per-group result. If the report needs every department, LEFT JOIN the result to the department list.
  • SQL Server uses OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY instead of LIMIT.

Common mistakes

  • SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) ...) works for N = 2 but does not generalise.
  • Forgetting DISTINCT with OFFSET, so a tie for first returns the top value again.
  • Using RANK, which skips numbers after ties and can find nothing for N.

More on this topic in the SQL Interview Questions guide, or browse all SQL questions.