Nth Highest Salary (Classic) in SQL
DENSE_RANK for ties; correlated COUNT fallback
Dense-rank window (DENSE_RANK() OVER (ORDER BY salary DESC), filter = N) handles ties correctly and reads clearly. Correlated COUNT (salaries greater than me = N-1) is the no-window fallback for old engines. LIMIT 1 OFFSET N-1 breaks on ties — two people sharing second place both deserve rank 2.
Rank distinct salaries
DENSE_RANK() OVER (ORDER BY salary DESC) — ties share, no gaps. The Nth-distinct engine.
Filter outside
Windows evaluate after WHERE — wrap in subquery/CTE, filter r = N outside (or QUALIFY where supported).
Know the siblings
ROW_NUMBER breaks ties arbitrarily; RANK gaps (1,1,3). LIMIT/OFFSET breaks on ties entirely.
Fallback without windows
Correlated COUNT (salaries greater than me = N-1) works on old engines — O(n²)-ish but portable.
1SELECT * FROM (SELECT *, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM employees) t WHERE r = 2;
| name | salary | r |
|---|---|---|
| Alice | 85000 | 2 |
Salaries ranked distinct: 91k→1, 85k→2, 73k→3… Alice alone holds rank 2. With a tie at 91k both would share rank 1 and Alice would still be rank 2 — LIMIT/OFFSET would have missed that.
Second-highest distinct
Ties handled — both 91k holders share rank 1.
1SELECT * FROM (SELECT *, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM employees) t WHERE r = 2;
| name | salary | r |
|---|---|---|
| Alice | 85000 | 2 |
No-window fallback
Correlated COUNT for MySQL 5 / old SQLite.
1SELECT name, salary FROM employees e1 WHERE (SELECT COUNT(*) FROM employees e2 WHERE e2.salary > e1.salary) = 1;
| name | salary |
|---|---|
| Alice | 85000 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.