SQL Percentiles

The median generalized — any percentile, not just the 50th.

What & Why

PERCENTILE_CONT(p) works for any p between 0 and 1 — the median from the previous lesson was just the special case p = 0.5.

See How It Works

BUSINESS QUESTION

Marketing wants median and 90th-percentile campaign spend by channel.

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
SELECT
  channel,
  ROUND(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY spend)::numeric, 2) AS p50_spend,
  ROUND(PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY spend)::numeric, 2) AS p90_spend
FROM marketing.campaigns
GROUP BY channel
ORDER BY channel;
RESULT — continuous spend percentiles
channelp50_spendp90_spend
email45000.0045000.00
google_ads57500.0059500.00
linkedin50000.0050000.00

The google_ads p90 interpolates between 55,000 and 60,000.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario