SQL Nth Highest Value
Generalize 'second highest' to any N — DENSE_RANK is what makes this trivial instead of painful.
What & Why
The nth-highest pattern ranks values in descending order and filters the desired rank. Dense ranking handles ties explicitly and extends cleanly from second-highest to any requested position.
See How It Works
BUSINESS QUESTION
Return every campaign tied for the third-highest spend value.
| id | name | channel | spend | start_date | end_date | status | target_segment |
|---|---|---|---|---|---|---|---|
| 1 | Spring Launch | google_ads | 55000.00 | 2024-01-15 | 2024-03-31 | active | smb |
| 2 | Retention Webinar | 45000.00 | 2024-02-10 | 2024-04-15 | active | enterprise | |
| 3 | Finance Retargeting | 50000.00 | 2024-03-12 | 2024-05-31 | active | enterprise | |
| 4 | Enterprise Search | google_ads | 60000.00 | 2024-04-01 | 2024-06-30 | active | enterprise |
Watch DENSE_RANK find the third distinct campaign spendStep 1 of 5
DENSE_RANK() OVER (ORDER BY spend DESC) = 3
| id | name | spend | spend_rank | result |
|---|---|---|---|---|
| 4 | Enterprise Search | 60,000.00 | 1 | SKIP |
| 1 | Spring Launch | 55,000.00 | 2 | SKIP |
| 3 | Finance Retargeting | 50,000.00 | 3 | KEEP |
| 2 | Retention Webinar | 45,000.00 | 4 | SKIP |
The highest distinct spend receives rank one.
EXAMPLE QUERY
WITH ranked AS (
SELECT
id,
name,
spend,
DENSE_RANK() OVER (ORDER BY spend DESC) AS spend_rank
FROM marketing.campaigns
)
SELECT id, name, spend
FROM ranked
WHERE spend_rank = 3
ORDER BY name, id;This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario