SQL · easy
Asked in Data Analyst interviews, in the SQL round.
Use a subquery with MAX where salary < (SELECT MAX(salary)), or DENSE_RANK() = 2.
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.
ORDER BY salary DESC LIMIT 1 OFFSET 1. It works on unique salaries and is wrong the moment two people earn the same amount.