Question presented to candidate:
"Given an employees table with a salary column, write a query that returns the third highest salary. Then make it work for any N, and tell me what your query does when two people earn the same amount, when some salaries are NULL, and when there are fewer than N distinct salaries."
What a strong answer should cover:
- Clarify "Nth highest": the Nth distinct salary value (ties count once) or the Nth row; the classic answer means distinct values
DENSE_RANK() OVER (ORDER BY salary DESC)and filter= N, which returns every employee at that salary; whyROW_NUMBER()andRANK()give different answers on ties- Without window functions:
SELECT DISTINCT salary ... ORDER BY salary DESC LIMIT 1 OFFSET N-1, or the correlated "N-1 distinct salaries are higher" subquery - Fewer than N salaries: a bare
LIMIT/OFFSETreturns no row; wrapping it in a scalar subquery returns NULL instead - NULL salaries: PostgreSQL sorts NULL first in
DESCorder, so the "highest" can be NULL unless you filter it or writeNULLS LAST; SQLite, MySQL and SQL Server sort it last inDESC - Per group (Nth highest per department) with
PARTITION BY, and the cost: one sort of the table, helped by an index onsalary
Clarifying questions expected:
- If two employees share the top salary, is the next one the 2nd or the 3rd highest?
- Should the result be the salary value or the employees who earn it?
- What should come back when there is no Nth salary: no row, or NULL?
Code / implementation expected: Yes β a DENSE_RANK() query, and one approach that works without window functions.
Schema used by the examples: