SQL Median

The middle value — Postgres computes it directly, no manual sorting-and-picking required.

What & Why

The median is the middle value in a sorted list — or the average of the two middle values, for an even count. PERCENTILE_CONT(0.5) computes this directly.

See How It Works

BUSINESS QUESTION

Marketing wants median 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 median_spend
FROM marketing.campaigns
GROUP BY channel
ORDER BY channel;
RESULT — median campaign spend by channel
channelmedian_spend
email45000.00
google_ads57500.00
linkedin50000.00

PERCENTILE_CONT interpolates the two google_ads spends to 57,500.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario