Window functions: totals without collapsing rows
You want each order listed with its customer’s total beside it, but GROUP BY squashes the orders into one row per customer. Window functions compute totals, running sums and ranks across related rows while keeping every row. Here is what OVER does, drawn one row at a time.
01 A total next to every row
A shop keeps one row per order. You want to list every order and, beside it, the customer’s total, so you can see what share of their spending each order was. GROUP BY gives you the totals, but it gives you only the totals.
SELECT customer, sum(amount) AS totalFROM ordersGROUP BY customer;customer | total----------+-------Ana | 53Ben | 62Cho | 59(3 rows)
id | customer | amount | total----+----------+--------+-------1 | Ana | 30 | 533 | Ana | 8 | 536 | Ana | 15 | 532 | Ben | 12 | 62...(8 rows)
Grouping folds each customer’s rows into one, so the individual orders are gone. The old fix is to group in a subquery and join it back to orders. A window function does the same thing in one expression, without the join and without losing a row. Every output on this page is a real run on Postgres 16; the syntax is standard SQL and works the same in MySQL 8, SQLite 3.25+ and SQL Server.
02 OVER: an aggregate that keeps the rows
Put OVER (...) after an aggregate and it stops collapsing rows. For each row, the database works out a window: the set of rows that belong with this one. It computes the aggregate over that window and writes the answer into the current row. PARTITION BY customer says the window is “all rows with the same customer as me”.
Eight rows in, eight rows out. An empty OVER () makes the whole result one window, which is how you get a share of the grand total:
Window functions run late: after FROM, WHERE, GROUP BY and HAVING, and before ORDER BY and LIMIT. So a window sees only the rows that survived the filters, and it may sit on top of a grouped query: avg(sum(amount)) OVER (...) averages the group sums.
03 Running totals: ORDER BY inside OVER
Add ORDER BY inside the brackets and the window changes meaning. It is no longer the whole partition: it is every row from the start of the partition up to the current one. A sum over that is a running total.
Postgres does not recompute each window from scratch. It sorts the rows by the partition key and then the order key, and walks them once, keeping a running state that it resets whenever the partition key changes.
- row being read
- row just output
- done
- not read yet
The Sort below the window step has already put the rows in order: by customer, then by day. Nothing has been output yet.
You can see both parts in the plan. The Sort lines the rows up; WindowAgg is the single pass on top.
The sort is the expensive part on a big table. An index on (customer, day) can hand the rows over already in order, and then the Sort node disappears. Several window functions with the same PARTITION BY and ORDER BY share one sort; different ones each need their own.
04 The frame: which rows the window sees
The rows an aggregate actually reads are called the frame. With ORDER BY and nothing else, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. The word RANGE hides a trap: rows that tie on the order key are peers, and the frame always includes all of a row’s peers. Order the whole table by day and the two orders on each day tie:
range_total jumps a whole day at a time: row 1 already includes row 2’s 12, because they are peers. rows_total counts physical rows, one at a time. Neither is wrong; pick on purpose. For a per-day running total, RANGE is what you want. For a running total per order, use ROWS and give ORDER BY a tie-breaker such as id, or the order among peers is up to the database.
Ties in the window’s ORDER BY change the answer silently. If a running total or a row_number() looks odd, check whether the order key is unique within each partition.
A frame can also slide. ROWS BETWEEN 1 PRECEDING AND CURRENT ROW reads only this row and the one before, which gives a two-day moving average when the rows are one per day:
| Inside OVER | Frame for each row |
|---|---|
| () | every row of the result |
| (PARTITION BY c) | every row with the same c |
| (PARTITION BY c ORDER BY d) | from the partition’s first row to this row and its peers (RANGE) |
| (... ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) | from the first row to exactly this row, ignoring ties |
| (... ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) | this row and the one before it |
05 Ranks: row_number, rank and dense_rank
Some functions exist only as window functions. The three ranking ones number the rows in the window’s order. They differ only in what they do with ties, and our data has one: Ben has two orders of 25.
| Function | Ties get | Next row gets | Use it for |
|---|---|---|---|
| row_number() | different numbers, in no promised order | 5 | exactly one row per slot: paging, de-duplicating |
| rank() | the same number | 5: it skips 4 | competition ranking: “joint 3rd, then 5th” |
| dense_rank() | the same number | 4: no gap | “the top 3 distinct amounts” |
Look at row_number: the first 25 printed got 4 and the second got 3. The two rows tie on amount, so Postgres was free to number them either way, and the outer ORDER BY happened to print them in the other order. Add a tie-breaker, ORDER BY amount DESC, id, whenever the numbers have to be stable.
06 Top N per group needs a subquery
“Each customer’s biggest order” is a ranking within each partition, then a filter. The obvious query fails, for the same reason WHERE cannot use sum: windows are computed after WHERE has already run.
Compute the rank in a subquery (or a WITH clause), then filter its output:
rn <= 3 gives the top three per customer. The choice of function matters here too: Ben’s top two orders are both 25. row_number returns one of them; rank would return both, since both rank 1. Leaderboards usually want rank so that joint winners all show.
07 Looking at the row before: lag and lead
lag(col) reads col from the previous row in the window’s order, and lead(col) from the next one. That turns “change since last time” into a single expression, with no self-join.
The first row of each partition has no previous row, so lag returns NULL and the subtraction does too. lag(amount, 1, 0) supplies a default instead. lag and lead ignore the frame; they always count rows from the current one within the partition.
08 When it bites
last_value(amount) OVER (PARTITION BY customer ORDER BY day)last_value returns the current rowThe default frame ends at the current row, so the “last” row it sees is this one. Ana’s rows came back 30, 8, 15 instead of 15, 15, 15. Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or use first_value with ORDER BY day DESC.sum(amount) OVER (ORDER BY day)Ties make the running total jumpWith the default RANGE frame, rows on the same day are peers and all get the day’s total. Use ROWS and a unique order key for a row-by-row total.WHERE rank() OVER (...) = 1Filtering on a window in WHEREWindows run after WHERE. Rank in a subquery or CTE, then filter in the outer query.row_number() OVER (ORDER BY score DESC)row_number on a key with tiesTied rows get different numbers in an order nobody promised, and the numbers can change between runs. Add a tie-breaker, or use rank if ties should share a place.SELECT ..., count(*) OVER () FROM orders LIMIT 10Expecting LIMIT to shrink the windowLIMIT runs after windows, so count(*) OVER () counts every row that passed WHERE, not the 10 you get. That is handy for “page 1 of N”, but it also means the database computes the window over all of them.