Video in progress
How does `SUM(amount) OVER (ORDER BY day)` compute a running total, and how does that differ from GROUP BY?
A window function doesn't merge rows: each row stays in place and gets a value computed over its "window" next to it. GROUP BY squeezes a group into one row. For a running total you use a window with ORDER BY.
📖 Answer
You have a table of daily revenue and want "the total up to that day" next to each row:
SELECT day,
amount,
SUM(amount) OVER (ORDER BY day) AS running_total
FROM daily_revenue;
| day | amount | running_total |
|---|---|---|
| 01 | 100 | 100 |
| 02 | 50 | 150 |
| 03 | 70 | 220 |
You can't do this with GROUP BY: it leaves one row per group and loses the amount column.
PARTITION BY splits the window into groups, and the calculation restarts in each group:
SUM(amount) OVER (PARTITION BY shop_id ORDER BY day)
A spot where people often slip in interviews: the default frame of a window with ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. If a day has two rows, RANGE treats them as "equal" and gives both the same total. If you want each row computed separately, write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Window functions are computed after WHERE, so you can't use them in WHERE: you wrap the query in a subquery or CTE and filter outside.
Sign up to mark studied questions and save your progress.