SQL OVER Clause

The one keyword that turns a normal aggregate into a window function.

What & Why

The OVER clause defines the rows available to a window function while leaving detail rows in the result. It separates a calculation's context from GROUP BY so totals, ranks, and comparisons can appear beside each row.

See How It Works

BUSINESS QUESTION

Compare a plain campaign-spend aggregate with full-table and channel-partitioned OVER results.

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 OVER change the aggregate result grainStep 1 of 3
SUM(spend) · no OVER
total_campaign_spend
210,000.00

A plain aggregate collapses all four campaign rows into one total row.

EXAMPLE QUERY
-- Plain aggregate: one result row
SELECT SUM(spend) AS total_campaign_spend
FROM marketing.campaigns;

-- Empty OVER: repeat the full total beside every campaign
SELECT
  id AS campaign_id,
  name,
  spend,
  SUM(spend) OVER () AS total_campaign_spend
FROM marketing.campaigns
ORDER BY spend DESC, campaign_id;

-- PARTITION BY: repeat a separate total inside each channel
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