SQL · easy

Write a query to find the second highest salary from an Employees table.

Asked in Data Analyst interviews, in the SQL round.

Short answer

Use a subquery with MAX where salary < (SELECT MAX(salary)), or DENSE_RANK() = 2.

How to answer it

Two answers are expected; the second is the one that shows you know window functions.

The subquery version reads naturally: the largest salary that is smaller than the largest salary.

SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

The window version generalises to "Nth highest" and handles ties the way the interviewer probably wants:

SELECT DISTINCT salary
FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
) ranked
WHERE rnk = 2;

DENSE_RANK, not RANK or ROW_NUMBER: if two people share the top salary, ROW_NUMBER would call one of them "second", and RANK would skip 2 entirely and return nothing. DENSE_RANK returns the second distinct value, which is what "second highest" means. If there is only one distinct salary, both queries return NULL or no row; say so before they ask.

Related questions

Practice this for real