SQL PARTITION BY

Splits the table into independent groups for the window function — without merging any rows together.

What & Why

PARTITION BY divides the rows into groups, and the window function is computed separately within each group. It's conceptually similar to GROUP BY — except every row survives, grouped or not.

See How It Works

BUSINESS QUESTION

Marketing wants every campaign beside total spend for its own 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
Watch PARTITION BY calculate one total per channelStep 1 of 3
SUM(spend) OVER (PARTITION BY channel)
campaign_idnamechannelspendchannel_spend
2Retention Webinaremail45,000.0045,000.00
4Enterprise Searchgoogle_ads60,000.00115,000.00
1Spring Launchgoogle_ads55,000.00115,000.00
3Finance Retargetinglinkedin50,000.0050,000.00

The email partition contains one campaign, so its channel total is 45,000.00.

EXAMPLE QUERY
SELECT
  id AS campaign_id,
  name,
  channel,
  spend,
  SUM(spend) OVER (PARTITION BY channel) AS channel_spend
FROM marketing.campaigns
ORDER BY channel, spend DESC, campaign_id;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario