We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium sql problem, graded against 4 test cases (2 of them hidden).
Query-writing problems - joins, aggregation, window functions, and query tuning.
Reach for it when you see: A schema and a question about the data rather than a function signature.
More SQLproblems →```sql
-- LIMIT / OFFSET form
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
OFFSET (n - 1) ROWS FETCH NEXT 1 ROW ONLY;
-- Postgres / SQL Server. MySQL: LIMIT 1 OFFSET (n - 1).
-- Window-function form (engine-portable)
WITH ranked AS (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM Employee
)
SELECT MAX(salary) FROM ranked WHERE rnk = n;
```
Why `DENSE_RANK`: ties at the top should not push the "Nth distinct" result down. `DENSE_RANK` gives 1, 1, 2, 3 - perfect for "distinct value rank". `ROW_NUMBER` would give 1, 2, 3, 4 and skip the duplicate, which is wrong for this question.
LeetCode-specific gotcha: the harness expects NULL when N is out of range, so use `MAX()` (returns NULL on empty group) instead of `SELECT salary ... LIMIT 1` which returns no rows.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.