SQL MAX OVER

The mirror of MIN OVER — the largest value in the window, on every row.

What & Why

MAX(column) OVER (PARTITION BY ...) finds each partition's largest value and repeats it on every row — same mechanics as MIN OVER, opposite direction.

See How It Works

BUSINESS QUESTION

Marketing wants each campaign beside the maximum spend in its 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
  id AS campaign_id,
  channel,
  spend,
  MAX(spend) OVER (PARTITION BY channel) AS channel_max_spend
FROM marketing.campaigns
ORDER BY channel, campaign_id;
RESULT — channel maximum beside campaigns
campaign_idchannelspendchannel_max_spend
2email45000.0045000.00
1google_ads55000.0060000.00
4google_ads60000.0060000.00
3linkedin50000.0050000.00

MAX OVER uses the highest spend in each channel partition.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario