Learn SQL/Advanced/Interview Patterns/SQL Nth Highest Value

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.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
Watch DENSE_RANK find the third distinct campaign spendStep 1 of 5
DENSE_RANK() OVER (ORDER BY spend DESC) = 3
idnamespendspend_rankresult
4Enterprise Search60,000.001SKIP
1Spring Launch55,000.002SKIP
3Finance Retargeting50,000.003KEEP
2Retention Webinar45,000.004SKIP

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.

Advanced business practice

Sign up free to try it on a real business scenario