The Nth Highest Salary SQL problem asks you to find the n-th highest distinct salary from an Employee table. If fewer than n distinct salaries exist, return NULL. This classic SQL problem tests dense ranking, subqueries, and offset-based selection.
Deloitte, Microsoft, Amazon, Google, Bloomberg, and Accenture ask this as a foundational SQL ranking problem. It tests knowledge of DENSE_RANK(), LIMIT/OFFSET, or subquery approaches. The database interview pattern is the core, and multiple valid SQL solutions exist — demonstrating knowledge of several earns extra credit.
Multiple approaches:
DENSE_RANK() OVER (ORDER BY salary DESC), filter WHERE rank = N.SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 1 OFFSET N-1 (wrapped to return NULL if no row).Salaries: [100, 90, 90, 80, 70]. N=2. Distinct sorted: [100, 90, 80, 70]. 2nd highest = 90.
N=5: only 4 distinct salaries exist. Return NULL.
OFFSET N-1.SQL ranking problems come in two flavors: with window functions (DENSE_RANK()) and without (subquery or LIMIT/OFFSET). Know both. The stored procedure approach (CREATE FUNCTION getNthHighestSalary(N INT)) is sometimes required in older SQL platforms. Always clarify: "distinct salaries" means 100, 90, 80 are three distinct values, not four when 90 appears twice. This distinction matters for rank counting.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Managers with at Least 5 Direct Reports | Medium | Solve | |
| Confirmation Rate | Medium | Solve | |
| Count Salary Categories | Medium | Solve | |
| Product Sales Analysis III | Medium | Solve | |
| Rank Scores | Medium | Solve |