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

SQL Second Highest Value

A classic — and there are three completely different ways to get it right.

What & Why

The Second Highest Value pattern is used to rank distinct values and select the second-highest position. This keeps the SQL aligned with one concrete business question and makes the result grain explicit before the query is reused.

See How It Works

BUSINESS QUESTION

Marketing wants every campaign tied for the second-highest spend.

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
EXAMPLE QUERY
WITH ranked AS (
  SELECT
    id AS campaign_id,
    name,
    spend,
    DENSE_RANK() OVER (ORDER BY spend DESC) AS spend_rank
  FROM marketing.campaigns
)
SELECT campaign_id, name, spend
FROM ranked
WHERE spend_rank = 2
ORDER BY campaign_id;
RESULT — second-highest campaign spend
campaign_idnamespend
1Spring Launch55000.00

Spring Launch has the second distinct spend after Enterprise Search.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario