Overview
Curated: · Written: · Reviewed:
Window Functions
In one line
A window function computes one value per input row from a set of related rows (its window) without collapsing them. Reach for it when a row needs group-level context beside its detail: a customer total on every order, a rank within a category, or the previous row's value for a period-over-period change.
Key definitions
- PARTITION BY: splits rows into independent groups. The calculation restarts at each boundary, and omitting it makes the whole result one partition.
- Window ORDER BY: sets the sequence for ranking, offset and frame functions. It is separate from the query's final ORDER BY, which only controls presentation.
- Frame: the rows an aggregate window sees. ROWS counts physical rows, RANGE works on values including peers, GROUPS counts peer groups.
- Peers: rows that tie on the window ORDER BY expression.
- Evaluation phase: windows run after FROM, WHERE, GROUP BY and HAVING, and before DISTINCT, ORDER BY and LIMIT.
How it works
Rows are partitioned, sorted by the window ORDER BY, and each row's frame is then evaluated. Because WHERE runs first, a window only sees rows that survived the filter. Because windows run after HAVING, a window result cannot appear in WHERE or HAVING, so top-N per group is a CTE or subquery that computes the rank, with the filter in the outer query. Windows can also run over aggregated rows: SUM(SUM(amount)) OVER () gives each group's share of the grand total in one pass.
When to use and when not to
| Need | Use | Why |
|---|---|---|
| Detail row plus group total | Window aggregate | Keeps every row |
| Top N per group | ROW_NUMBER in a CTE, filter outside | Window results cannot sit in WHERE |
| Previous or next row value | LAG or LEAD | Avoids a self-join |
| Only group-level output | GROUP BY | Cheaper, and no detail is needed |
| Ties must all count toward top N | RANK or DENSE_RANK | ROW_NUMBER breaks ties arbitrarily |
| Value needs rows outside its partition | Subquery or join | A window only sees its own partition |
Traps interviewers probe
- Running total jumps in steps. The default RANGE frame includes all peers, so every row with the same date shows that date's full total. Fix: ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
- LAST_VALUE returns the current row. Under the default frame the window ends at the current row. Fix: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. FIRST_VALUE works by accident under the default frame, which is why the asymmetry is easy to miss.
- A 7-row moving average is not a 7-day average. If a day is missing, ROWS 6 PRECEDING spans more calendar days. Fix: densify the series with a generated date range, or use RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW.
- Top three changes between runs. ROW_NUMBER with tied revenue is nondeterministic. Fix: add a unique tiebreaker such as the primary key to the ORDER BY. A timestamp recorded to the second is not unique enough.
Interview tips
Open with the contrast: "A window function returns one value per input row, computed over related rows, so unlike GROUP BY it keeps the detail."
Expect these follow-ups:
- ROW_NUMBER vs RANK vs DENSE_RANK on ties, and which one the stakeholder means.
- Why a window cannot be filtered in WHERE, and the nested shape that follows.
- The default frame and the running-total bug.
- Index order: an index on (partition key, order key) lets the planner skip the sort. The reversed index does not match the partition prefix, so a Sort appears.
- NULL placement: PostgreSQL treats NULL as larger than any value, so DESC puts NULLs first unless you add NULLS LAST.
- FILTER (WHERE ...) on an aggregate window, to compute several scoped measures in one pass.
30-second outline:
- Definition: one value per row, computed over a window, rows kept.
- Mechanics: PARTITION BY restarts the calculation, the window ORDER BY sets the sequence, and the frame sets the rows.
- Trap: the default RANGE frame and peers, so say ROWS for a running total.
- Shape: windows run after WHERE and HAVING, so filter on a rank in an outer query.
- Determinism: add a unique tiebreaker to the ORDER BY.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.