SQL Window Frames
The third piece of a window definition — exactly which rows within the partition are visible.
What & Why
A window frame narrows an ordered partition with ROWS or RANGE boundaries such as unbounded preceding and current row. Frames distinguish a running metric from a moving metric and prevent surprising LAST_VALUE or cumulative results.
See How It Works
BUSINESS QUESTION
Calculate a seven-row rolling active-user total.
| date_day | dau | new_users | returning_users |
|---|---|---|---|
| 2024-04-01 | 1240 | 180 | 1060 |
| 2024-04-02 | 1315 | 205 | 1110 |
| 2024-04-03 | 1288 | 164 | 1124 |
| 2024-04-04 | 1392 | 221 | 1171 |
EXAMPLE QUERY
SELECT
date_day,
dau,
SUM(dau) OVER (
ORDER BY date_day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS rolling_7_row_dau
FROM growth.daily_active_users
ORDER BY date_day;RESULT — rolling seven-row DAU sum
| date_day | dau | rolling_7_row_dau |
|---|---|---|
| 2024-04-01 | 1240 | 1240 |
| 2024-04-02 | 1315 | 2555 |
| 2024-04-03 | 1288 | 3843 |
| 2024-04-04 | 1392 | 5235 |
Only four source rows exist, so every frame begins at the first representative day.
This lesson's practice is part of Pro.
Sign up free to try it on a real business scenario