Q&A-1Explain what a window function is and when you would reach for one.
Answer
The 90-second answer. A window function computes a value across a set of rows related to the current row, the window, and returns one value per input row. It never collapses rows. GROUP BY reduces many rows to one per key and throws the detail away; a window function keeps every row and attaches the computed value to it.
The selection test: do I still need the individual rows in the output? "Total revenue per region" collapses: GROUP BY. "Every order, with its region's total and its rank inside that region" does not: window.
Syntax is a function call plus OVER (...). PARTITION BY divides rows into independent groups so the calculation restarts at each boundary; ORDER BY inside OVER sequences rows for ranking, offset functions and frames, and is independent of the query's final ORDER BY, which only affects presentation. Families: ranking (ROW_NUMBER, RANK, DENSE_RANK, NTILE), offset (LAG, LEAD, FIRST_VALUE, LAST_VALUE), and ordinary aggregates used as windows (SUM, AVG, COUNT with OVER). Reach for one for ranking within groups, running totals and moving averages, period-over-period deltas, share-of-group, and dedup by picking one row per key. Self-joins and correlated subqueries can express most of these, but the window version is usually one pass and far easier to read.
What breaks. Three things bite in practice.
The default frame. With ORDER BY inside OVER and no explicit frame, the frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. That is what makes a running total work, and what makes LAST_VALUE return the current row, not the last row of the partition. Trace it on orders(region, order_id, amount):
| region | order_id | amount | SUM ... ORDER BY order_id | LAST_VALUE default | LAST_VALUE full frame |
|---|---|---|---|---|---|
| EU | 1 | 100 | 100 | 100 | 200 |
| EU | 2 | 300 | 400 | 300 | 200 |
| EU | 3 | 200 | 600 | 200 | 200 |
| US | 4 | 50 | 50 | 50 | 50 |
The full-frame column is ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. Also note RANGE includes peers, rows tying on the ORDER BY key, so a running total over duplicate keys jumps by the whole peer group at once; use ROWS when you want strict row-by-row.
Sort cost. ORDER BY inside OVER forces the rows into order. Postgres can skip the sort only when an index's leading columns match PARTITION BY followed by ORDER BY; otherwise it sorts, and the sort is per partition. A window with no PARTITION BY over a large table is one global sort of the whole input.
Memory. The sort buffers rows and spills to temp files once it exceeds work_mem (4 MB default in Postgres). One huge partition (PARTITION BY a low-cardinality column, or none at all) means one huge sort; many small partitions stay in memory. Watch for temp-file growth and Sort Method: external merge in EXPLAIN (ANALYZE).
Two more, quickly: window functions are evaluated after WHERE/GROUP BY/HAVING, so WHERE rn = 1 is an error. Wrap it in a subquery or CTE. And ROW_NUMBER dedup is nondeterministic on ties; add a tiebreaker to the ORDER BY or you will pick a different row on a different plan.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.