Lesson 33 / 37 · Windows

A window function looks at other rows without collapsing them

The running total is computed per customer (PARTITION BY) in date order (ORDER BY), and every order keeps its own row. Compare with GROUP BY, which would leave one row per customer.

The query

SELECT id, customer_id, order_date, amount,
       sum(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS running_total
FROM orders
WHERE amount IS NOT NULL

Try removing ORDER BY order_date from the window: every order then gets its customer's full total, not a running one.

Next: LAG reads the previous row · All lessons