Nth Highest Salary (DENSE_RANK)
sqlSQLinterview-prepintermediate
The classic interview question: find the 2nd (or Nth) highest salary, treating employees on the same salary as one rank.
-- Second highest salary. Change 2 to the N you need.
-- DENSE_RANK keeps ties together, so people on the same salary share a rank and no rank is skipped.
-- The rank is calculated in a CTE because window functions cannot be used directly in WHERE.
WITH ranked AS (
SELECT salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
WHERE salary IS NOT NULL
)
SELECT DISTINCT salary
FROM ranked
WHERE salary_rank = 2;
-- Alternative (SQL Server 2012+ and PostgreSQL): skip N-1 distinct salaries, take one.
-- SELECT DISTINCT salary
-- FROM employees
-- WHERE salary IS NOT NULL
-- ORDER BY salary DESC
-- OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;