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.
| id | name | channel | spend | start_date | end_date | status | target_segment |
|---|---|---|---|---|---|---|---|
| 1 | Spring Launch | google_ads | 55000.00 | 2024-01-15 | 2024-03-31 | active | smb |
| 2 | Retention Webinar | 45000.00 | 2024-02-10 | 2024-04-15 | active | enterprise | |
| 3 | Finance Retargeting | 50000.00 | 2024-03-12 | 2024-05-31 | active | enterprise | |
| 4 | Enterprise Search | google_ads | 60000.00 | 2024-04-01 | 2024-06-30 | active | enterprise |
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_id | name | channel | spend | total_campaign_spend |
|---|---|---|---|---|
| 4 | Enterprise Search | google_ads | 60000.00 | 210000.00 |
| 1 | Spring Launch | google_ads | 55000.00 | 210000.00 |
| 3 | Finance Retargeting | 50000.00 | 210000.00 | |
| 2 | Retention Webinar | 45000.00 | 210000.00 |
The window total repeats while campaign grain remains intact.
This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario