Skip to content
Tech Interview Prep
Technical interview guide

Window Functions

Per-row calculations across a related set of rows (running totals, rankings, and row-over-row comparisons) without collapsing rows like GROUP BY does.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: SQL principles with PostgreSQL 18 examples; vendor-specific behavior must be verified.

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

FROM and WHERE GROUP BY and HAVING Window functions in SELECT DISTINCT, ORDER BY, LIMIT

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

NeedUseWhy
Detail row plus group totalWindow aggregateKeeps every row
Top N per groupROW_NUMBER in a CTE, filter outsideWindow results cannot sit in WHERE
Previous or next row valueLAG or LEADAvoids a self-join
Only group-level outputGROUP BYCheaper, and no detail is needed
Ties must all count toward top NRANK or DENSE_RANKROW_NUMBER breaks ties arbitrarily
Value needs rows outside its partitionSubquery or joinA window only sees its own partition

Traps interviewers probe

  1. 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.
  2. 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.
  3. 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.
  4. 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:

  1. Definition: one value per row, computed over a window, rows kept.
  2. Mechanics: PARTITION BY restarts the calculation, the window ORDER BY sets the sequence, and the frame sets the rows.
  3. Trap: the default RANGE frame and peers, so say ROWS for a running total.
  4. Shape: windows run after WHERE and HAVING, so filter on a rank in an outer query.
  5. 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.