Learn SQL/Advanced/Window Functions/Understanding SQL Windows

Understanding SQL Windows

The 'window' is just the set of rows visible to the function for each row it processes.

What & Why

For every row, a window function looks at a defined slice of the table — its window — and computes a value from that slice. The window can be the whole table, one partition, or a moving range of nearby rows, depending on how you define it.

See How It Works

BUSINESS QUESTION

Marketing wants each campaign beside total spend across the complete campaign window.

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,
  name,
  channel,
  spend,
  SUM(spend) OVER () AS total_campaign_spend
FROM marketing.campaigns
ORDER BY spend DESC, campaign_id;
RESULT — total spend beside detail
campaign_idnamechannelspendtotal_campaign_spend
4Enterprise Searchgoogle_ads60000.00210000.00
1Spring Launchgoogle_ads55000.00210000.00
3Finance Retargetinglinkedin50000.00210000.00
2Retention Webinaremail45000.00210000.00

The window total repeats while campaign grain remains intact.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario