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.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain 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):

regionorder_idamountSUM ... ORDER BY order_idLAST_VALUE defaultLAST_VALUE full frame
EU1100100100200
EU2300400300200
EU3200600200200
US450505050

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:

Difficulty: Medium
Q&A-23

Explain how a window function's ORDER BY differs from the query's ORDER BY.

Answer

They serve unrelated purposes and are entirely independent.

The ORDER BY inside OVER sequences rows for the calculation: it decides what 'previous' means for LAG, what order ranks are assigned in, and which rows fall inside a frame. It affects the computed values.

The query's own ORDER BY sorts the output. It affects presentation only, and it runs after the windows have already been computed.

They often differ, and legitimately. A query might rank orders by amount descending inside the window but present the result sorted by customer name: RANK() OVER (ORDER BY amount DESC) with a final ORDER BY customer_name. Both are correct and neither influences the other.

The mistake this causes is assuming the window's ordering also orders the result. It does not. A query with a window ORDER BY created_at and no final ORDER BY has no guaranteed output order at all: the rows may come back in whatever order the plan produces, and it will often coincidentally look sorted in testing and not in production. If the output should be ordered, the query needs its own ORDER BY, always.

The reverse mistake is adding a final ORDER BY and expecting it to fix a ranking that was computed over the wrong sequence. It cannot: by then the ranks are already assigned.

A practical consequence worth knowing is that if both orderings happen to match, the engine may satisfy them with a single sort, so aligning them when there is no reason to differ is a small free optimisation, provided the alignment is genuine and not a coincidence someone later relies on.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Compare ROW_NUMBER, RANK and DENSE_RANK, and say how you choose.

Answer

ROW_NUMBER assigns 1, 2, 3 with no ties ever: tied rows get arbitrary distinct numbers. RANK gives tied rows the same rank and then skips the consumed numbers: 1, 2, 2, 4. DENSE_RANK gives the same rank without skipping: 1, 2, 2, 3.

How I choose comes down to what the requirement means when there is a tie, which is a question I ask rather than answer myself.

ROW_NUMBER when I need exactly N rows and any tie-break is acceptable: pagination, deduplication, picking one row per key. Deduplication is its most common use: number rows within a business key ordered by whatever should win, then keep number 1.

RANK when ties should genuinely share a position and the gap is meaningful: competition standings, where two silver medals mean no bronze. 'Top three products' with RANK returns four rows when two tie for third, which is usually what a stakeholder actually wants.

DENSE_RANK when I want distinct levels without gaps: 'the three highest distinct salary bands' rather than the three highest-paid people.

The practical point I would raise unprompted: engineers reach for ROW_NUMBER by habit, and stakeholders usually mean RANK. If two products tie exactly for third and the report shows only one, that is a defect from the business's point of view even though the SQL is correct.

And whichever I use, the ORDER BY needs a unique tiebreaker. With ROW_NUMBER and a non-unique ordering the assignment is nondeterministic, so the same query returns different 'top three' rows on different runs, which is very hard to debug when someone reports it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Explain how NULLs affect window function results: where they sort in a window ORDER BY, how ROW_NUMBER, RANK and DENSE_RANK treat them, and what they do to window aggregates.

Answer

Three behaviours, one rule: PostgreSQL sorts NULL as if it were larger than any non-null value, and treats all NULLs as equal to each other. Everything below follows from that.

Window ORDER BY. The default is NULLS LAST for ASC and NULLS FIRST for DESC. So RANK() OVER (ORDER BY score DESC) hands rank 1 to the NULL rows, not to the highest score. If that placement is wrong, say so: ORDER BY score DESC NULLS LAST.

Ranking. Because all NULLs are peers, RANK and DENSE_RANK give every NULL the same rank, and the next non-null value skips accordingly. ROW_NUMBER still hands out distinct numbers, but which NULL gets 1, 2 and 3 is arbitrary: it depends on the plan and can change between runs. Never rely on it. CUME_DIST and PERCENT_RANK inherit the same peer behaviour: every NULL gets the same value.

Aggregates. SUM, AVG, MIN, MAX and COUNT(expr) ignore NULL inputs; COUNT(*) does not. A running SUM therefore stays NULL until the first non-null row and then jumps: it does not accumulate from zero. AVG is the sharper trap: its divisor is the count of non-null values in the frame, not the frame size, so a running average over a six-row frame may be dividing by three.

All of it on one table:

sql CREATE TABLE scores (id int, student text, score int); INSERT INTO scores VALUES (1,'ana',90),(2,'bo',NULL),(3,'cy',70),(4,'di',NULL),(5,'eve',90),(6,'fay',NULL);

SELECT student, score, ROW_NUMBER() OVER (ORDER BY score DESC) AS rn, RANK() OVER (ORDER BY score DESC) AS rnk, DENSE_RANK() OVER (ORDER BY score DESC) AS drnk, SUM(score) OVER (ORDER BY score DESC) AS running_sum, AVG(score) OVER (ORDER BY score DESC) AS running_avg FROM scores;

studentscorernrnkdrnkrunning_sumrunning_avg
boNULL111NULLNULL
diNULL211NULLNULL
fayNULL311NULLNULL
ana9044218090.00
eve9054218090.00
cy7066325083.33

Two things there read like bugs and are not. The running sum is NULL for the first three rows and then jumps to 180, because SUM ignores NULLs and the default frame is RANGE UNBOUNDED PRECEDING AND CURRENT ROW: in RANGE mode CURRENT ROW means the last peer, so ana and eve share a frame and both see 180. And the running average at cy is 250/3, not 250/6: three of the six rows contributed nothing to the numerator or the denominator.

PARTITION BY behaves the same way. All NULL keys land in a single partition, because grouping treats NULLs as equal, so a report partitioned by region silently grows a "region = NULL" bucket.

LAG and LEAD return NULL both when the offset falls outside the partition and when the value sitting there is NULL. If the difference matters, carry a ROW_NUMBER() alongside and test it, or use a sentinel value. first_value, last_value and nth_value pass NULLs through the same way.

Fixes, in order of preference: put NULLS LAST (or FIRST) in the window ORDER BY when the placement is wrong; COALESCE(score, 0) when a NULL should count as zero; FILTER (WHERE score IS NOT NULL) when you want an explicit denominator; and choose COUNT(*) versus COUNT(score) deliberately rather than by accident. If NULLs should not be ranked at all, filter them in a CTE before the window: a window result cannot be filtered in the same query's WHERE, since windows are evaluated after it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Write a query returning each customer's three most recent orders, and explain its shape.

Answer

SQL
WITH ranked AS (
  SELECT o.*,
         ROW_NUMBER() OVER (
           PARTITION BY customer_id ORDER BY created_at DESC, id DESC
         ) AS recency
  FROM orders o
  WHERE created_at >= :since
)
SELECT * FROM ranked WHERE recency <= 3 ORDER BY customer_id, recency;

The nesting is forced, not stylistic. Window functions are evaluated in the SELECT phase (after WHERE, GROUP BY and HAVING) so recency has no value yet when WHERE runs. You cannot filter on it in the same query that defines it, and you cannot reference the alias in WHERE, GROUP BY or HAVING in any engine. Wrapping it in a CTE and filtering outside is the standard shape. (Window functions are SQL:2003; Postgres, SQL Server, Oracle, MySQL 8.0+ and SQLite 3.25+ have them. MySQL 5.7 does not: there you need a correlated subquery or a self-join.)

The tiebreaker is not optional. id DESC makes the ordering total. Without it, rows sharing a created_at are numbered arbitrarily and "the three most recent" can differ between identical runs. ROW_NUMBER rather than RANK because the requirement says three orders; RANK would mean "all orders at the three most recent timestamps" and can return more. Trace it on one customer:

idcreated_atROW_NUMBERRANK
405-05 12:0011
305-03 09:0022
205-03 09:0032
505-03 09:0042
105-01 08:0055

recency <= 3 returns {4,3,2} under ROW_NUMBER and {4,3,2,5} under RANK. Confirm which the requirement means before shipping.

Filter placement changes the answer. The WHERE inside the CTE filters before the window, so the ranking is over the filtered set. If the requirement were "the three most recent overall, but only display those since a date", the filter moves to the outer query: the two produce different rows whenever a customer has three orders newer than :since.

The alternative worth knowing: LATERAL.

SQL
SELECT c.id AS customer_id, o.*
FROM customers c
LEFT JOIN LATERAL (
  SELECT * FROM orders o
  WHERE o.customer_id = c.id AND o.created_at >= :since
  ORDER BY o.created_at DESC, o.id DESC
  LIMIT 3
) o ON true;

This does a top-3 index scan per customer instead of sorting every filtered order. On a table where the window version sorts 10M rows, the LATERAL version touches roughly customers × 3 index entries. It wins when the customer count is small relative to the order count; it loses when you need the whole result set ranked anyway, or when the planner misestimates and picks a sequential scan per customer. LEFT JOIN ... ON true keeps customers with no orders; CROSS JOIN LATERAL drops them: the window version also drops them, since they contribute no rows.

DISTINCT ON (customer_id) is not a substitute: it gives the top one per group, not the top three.

Cost. CREATE INDEX ON orders (customer_id, created_at DESC, id DESC); matches both the partition and the order keys, so the window version can read pre-sorted input and skip the sort node; the LATERAL version gets a bounded index scan per customer. Check the plan for a Sort node above the CTE, if it is there, the index is not being used for ordering. A large sort spills to temp files once it exceeds work_mem (default 4MB), which is where the window version's cost shows up.

Failure modes. Ties without a tiebreaker give nondeterministic output. created_at nullable: Postgres sorts DESC as NULLS FIRST, so a NULL timestamp ranks as the most recent order. Add NULLS LAST or make the column NOT NULL. And if the query is for a single customer, none of this is needed: plain ORDER BY created_at DESC, id DESC LIMIT 3 is correct and cheaper.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

How do you deduplicate rows keeping a specific survivor per key?

Answer

Number the rows within each key by whatever should decide the survivor, then keep number 1:

SQL
WITH numbered AS (
  SELECT *, ROW_NUMBER() OVER (
           PARTITION BY LOWER(TRIM(email))
           ORDER BY updated_at DESC, id DESC
         ) AS copy
  FROM users
)
SELECT * FROM numbered WHERE copy = 1;

ROW_NUMBER rather than RANK because I want exactly one row per key: RANK would return several when the ordering ties, defeating the purpose.

The partition expression matters as much as the function. Grouping on the raw column misses duplicates differing only in case or surrounding whitespace, which is the most common reason a deduplication pass 'finds nothing' while duplicates plainly exist. Normalising in the PARTITION BY catches them.

The ORDER BY encodes the survivorship rule, and that is a business decision rather than a technical one: most recently updated, most complete, earliest created, or the one with a verified flag. I would get it stated explicitly rather than defaulting to whatever seems natural, because the wrong survivor is a data-loss bug that is hard to detect later. id DESC is there as a tiebreaker so the choice is at least deterministic.

For actually deleting rather than selecting, the same CTE drives a delete of copy > 1, but first I check what references the losing rows and repoint those to the survivor, run it in a transaction, and inspect the affected count before committing. Deleting parents out from under children is the way this goes wrong.

And afterwards I add the unique constraint that should have existed. Cleaning duplicates without constraining the key guarantees they return, usually within days, and the second cleanup is harder because some of the duplicates now have their own history.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How would you compute each product's share of its category's revenue in one query?

Answer

Aggregate to one row per product, then use a window over those aggregated rows to get the category total on each one:

SQL
SELECT
  category_id,
  product_id,
  SUM(amount) AS revenue,
  SUM(SUM(amount)) OVER (PARTITION BY category_id) AS category_revenue,
  ROUND(100.0 * SUM(amount)
        / NULLIF(SUM(SUM(amount)) OVER (PARTITION BY category_id), 0), 2) AS pct_of_category
FROM order_lines
GROUP BY category_id, product_id;

The nested aggregate looks wrong at first glance and is exactly right. Window functions are evaluated after GROUP BY, so the window operates on the already-grouped rows: the inner SUM(amount) produces each product's revenue, and the outer windowed SUM adds those up across the category. It is one pass.

The alternatives are worse. A self-join to a category-totals subquery reads the table twice and needs its own grouping. A correlated scalar subquery per row re-reads the table for every product. Both produce the same numbers more slowly and less readably.

NULLIF(..., 0) guards the division. A category whose revenue nets to zero (entirely refunded, say) would otherwise raise a division-by-zero error and fail the whole report rather than the one row. Returning NULL for that row is the more useful failure.

If I needed the share of the overall total as well, SUM(SUM(amount)) OVER () with an empty window gives the grand total on every row, and both can appear in the same query.

The one thing to watch is that the window sees only rows surviving WHERE, so a date filter makes these shares 'share within the filtered period': correct, and worth stating in the report's labelling so nobody compares it against an unfiltered figure.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Explain window frames, and describe a bug the default frame causes.

Answer

The frame decides which rows within the partition a calculation actually sees. Without ORDER BY inside OVER, the frame is the whole partition. With ORDER BY and no explicit frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and that default is the bug.

RANGE is value-based. It includes every row that is a peer of the current row, tied on the ordering expression, as a unit. So a running total written SUM(amount) OVER (ORDER BY order_date) on data with several orders per date does not accumulate within a date. Every row for a given date shows that entire date's cumulative total. The output is monotonic, plausible, and wrong, and there is no error to alert you.

ROWS is positional and has no peer concept, so ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW accumulates strictly one row at a time. The rule I follow is: if I write a running total, I write ROWS explicitly.

GROUPS counts distinct peer groups, which is the right tool for 'the previous three distinct dates' regardless of how many rows each has.

The other frame trap is asymmetric and easy to miss. FIRST_VALUE works as expected under the default frame, but LAST_VALUE(x) OVER (ORDER BY y) returns the current row's value, because the frame ends at the current row, so the last visible row is the current one. It needs ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING. Because FIRST_VALUE behaves, people assume LAST_VALUE does too.

Frames also make moving calculations expressible, and there the trap is that 6 PRECEDING under ROWS means six rows, not six days, so with missing days a 'seven-day' average silently spans more calendar time. For a genuinely calendar-based window, either densify the series first or use a RANGE frame with an interval offset.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

A running total looks wrong: it jumps in steps instead of accumulating. Diagnose it.

Answer

The symptom names the cause: that is the default frame's peer behaviour.

When ORDER BY appears inside OVER with no frame clause, the frame defaults to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE is value-based: every row tied on the ordering expression is a peer and enters the frame together. So if the ordering is a date with several rows per date, every row for a given date shows that whole date's cumulative total, and the total advances in steps rather than row by row.

I confirm it by checking whether the ordering expression has duplicates, GROUP BY order_date HAVING COUNT(*) > 1, and by looking at whether the step boundaries line up with those duplicate values. If they do, that is conclusive.

The fix is to state ROWS explicitly: SUM(amount) OVER (ORDER BY order_date, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). I add the tiebreaker at the same time, because with ROWS and a non-unique ordering the accumulation order among tied rows is arbitrary, so the intermediate values, though they now advance one row at a time, are not reproducible between runs. Both changes are needed for a defensible answer.

It is worth saying that the default is not a mistake in the language: RANGE peer semantics are exactly right for 'cumulative total as of this date', where all rows on a date genuinely should show the same figure. The bug is that it is the default, so you get value-based semantics when you meant positional ones without having chosen either.

The general lesson I draw is to write the frame explicitly whenever ORDER BY appears inside OVER. It costs a line and removes a class of silent defect, and in review, an OVER (ORDER BY ...) with no frame is something I now always ask about.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How would you compute a seven-day moving average correctly?

Answer

The naive version is AVG(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), and it is wrong in two ways that both pass unnoticed.

First, ROWS counts rows, not days. If any day has no data, that window spans more than seven calendar days: a 'seven-day average' quietly covering nine. Second, if a day has several rows, the window covers less than a day of history.

There are two correct approaches. Aggregate to exactly one row per day first, then apply the row-based window, which also fixes the multiple-rows case:

SQL
WITH daily AS (
  SELECT d.day, COALESCE(SUM(o.amount), 0) AS amount
  FROM generate_series(:start, :end, interval '1 day') AS d(day)
  LEFT JOIN orders o ON o.created_at >= d.day AND o.created_at < d.day + interval '1 day'
  GROUP BY d.day
)
SELECT day, AVG(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
FROM daily;

The generated calendar is what makes the row-based window trustworthy: every day exists, so six preceding rows really are six preceding days. The COALESCE matters too: without it, no-activity days come back NULL and AVG skips them, which reintroduces the gap problem through a different door.

The alternative is a time-based frame, RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW, which is defined in time and needs no densification. It is more direct where the engine supports interval offsets, though support is less universal than ROWS.

Either way, the leading edge needs handling: the first six rows average over fewer than seven days, so they are noisier and not comparable with the rest. I exclude or mark them rather than charting a ramp that is an artefact of the window filling up. And the trailing edge matters just as much: today's partial day drags the average down and looks like a decline, so I exclude the incomplete period or label it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Explain FIRST_VALUE and LAST_VALUE, including the trap.

Answer

Both return a value from a specific position in the frame: FIRST_VALUE(x) from its first row, LAST_VALUE(x) from its last. NTH_VALUE(x, n) generalises them.

The trap is that they behave asymmetrically under the default frame, and the asymmetry is what makes it dangerous. With ORDER BY inside OVER and no explicit frame, the frame runs from the partition start to the current row. So FIRST_VALUE returns the partition's genuine first row: correct, matching intuition. LAST_VALUE returns the current row's own value, because the current row is the last one in that frame.

So LAST_VALUE(status) OVER (PARTITION BY order_id ORDER BY changed_at) does not give the final status. It gives each row's own status, which means the column looks populated and plausible and is simply a copy of another column. Because FIRST_VALUE works, people reasonably assume its counterpart does too, and the defect survives review.

The fix is an explicit full frame: LAST_VALUE(status) OVER (PARTITION BY order_id ORDER BY changed_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING).

In practice I often avoid it. FIRST_VALUE with the ordering reversed gives the same answer with less to get wrong, and for one row per partition ROW_NUMBER() = 1 or DISTINCT ON is clearer still. I reach for LAST_VALUE mainly when I need both ends in the same query and reversing is not available.

The broader habit: whenever ORDER BY appears inside OVER, write the frame explicitly. It costs one line and eliminates both this trap and the running-total peer bug in one stroke.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

How would you compute a customer's first and most recent order in one query?

Answer

If I only need the dates, aggregates are simplest and no window is required: MIN(created_at) and MAX(created_at) grouped by customer, one pass.

The question usually means more than the dates, though: the first order's amount and the latest order's status, say. MIN and MAX cannot give me a different column from the row where the extreme occurred, and that is where windows earn their place:

SQL
SELECT DISTINCT
  customer_id,
  FIRST_VALUE(created_at) OVER w AS first_order_at,
  FIRST_VALUE(amount)     OVER w AS first_amount,
  LAST_VALUE(created_at)  OVER w AS latest_order_at,
  LAST_VALUE(status)      OVER w AS latest_status
FROM orders
WINDOW w AS (
  PARTITION BY customer_id ORDER BY created_at, id
  ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
);

The explicit full frame is essential. Under the default frame LAST_VALUE returns each row's own value, so latest_status would be a copy of status: populated, plausible, wrong. The named WINDOW clause declares the definition once so all four functions share a single sort, and so the frame cannot drift between them under later editing.

I would usually prefer a form that does not depend on remembering the frame, though. Aggregating with conditional selection, or two ROW_NUMBER passes filtered to first and last and joined, is more verbose but harder to get silently wrong. In PostgreSQL specifically, two DISTINCT ON queries (one ordered ascending, one descending) joined on the customer, is very readable.

The DISTINCT above is doing real work and is worth noticing: the window returns one row per order, all identical within a customer, so it collapses them. That is acceptable here but it is a whole-row deduplication over a potentially large result, so on a big table I would compare it against the ROW_NUMBER-filtered form rather than assume it is cheaper.

And the tiebreaker id matters: two orders sharing a timestamp otherwise make 'first' and 'latest' ambiguous and non-reproducible.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do LAG and LEAD work, including the offset and default arguments, and how would you use them to compare each row with the previous one?

Answer

LAG and LEAD are window functions that return an expression evaluated at a row a fixed number of rows away from the current one, inside the same partition. LAG(x) is the value of x on the previous row, LEAD(x) on the next. The signature is lag(value [, offset [, default]]): offset defaults to 1, and default defaults to NULL and is what you get when the offset row does not exist. The first row of each partition for LAG, the last for LEAD. Both offset and default are evaluated with respect to the current row, so they can be expressions rather than literals, and default must be type-compatible with value.

The thing to say first: "previous" is defined entirely by the OVER clause's ORDER BY. With no ordering, the row order inside the partition is whatever the plan produces and LAG is meaningless. And LAG/LEAD are not restricted by the frame clause: unlike first_value, last_value and nth_value, they see the whole partition, so ROWS BETWEEN CURRENT ROW AND CURRENT ROW does not stop them reaching back.

Comparing each row with the previous one:

sql SELECT day, revenue, revenue - LAG(revenue) OVER (ORDER BY day) AS delta, ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY day)) / NULLIF(LAG(revenue) OVER (ORDER BY day), 0), 1) AS pct_change FROM daily_revenue ORDER BY day;

Trace over four rows:

dayrevenueLAG(revenue)deltapct_change
2024-01-01100NULLNULLNULL
2024-01-021301003030.0
2024-01-03120130-10-7.7
2024-01-0412012000.0

The first row's LAG is NULL, so delta is NULL: correct, there is no previous day. If you want 0 instead, pass the default: LAG(revenue, 1, revenue) compares the first row to itself and yields delta 0. Do not pass 0 as the default for a percentage change: the denominator becomes 0 and you get a division-by-zero error, which is why the query uses NULLIF rather than a default.

Per-entity comparison is the same query with PARTITION BY: LAG(revenue) OVER (PARTITION BY product_id ORDER BY day) restarts at each product.

Failure modes worth naming:

  • Ties. If two rows share the ORDER BY value, which one is "previous" is unspecified. Add a unique tiebreaker, ORDER BY day, id, or the report changes between plans.
  • NULLs are not skipped. LAG returns the value at that row even when it is NULL, so a gap in the data gives a NULL delta, not the last known value. "Previous non-NULL" is a different problem; PostgreSQL has no IGNORE NULLS for LAG.
  • Missing periods. LAG compares to the previous row present, not the previous day. If days are missing, it is the last reported day, not yesterday. Compare on the date difference when that matters.
  • Frame confusion. Adding a frame clause changes nothing for LAG/LEAD; people add one expecting it to.

Alternatives: a self-join on day = day - 1 or a correlated subquery gives the same answer, but both are a join or a per-row lookup, while LAG is one sort of the partition. That sort is the cost, and an index on (partition_key, order_key) can supply the ordering so the planner skips it. Reach for the self-join when you must match on a value rather than a row position, "the row with the largest day strictly less than this one", which LAG cannot express.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Explain how you would detect gaps in a sequence of events using window functions.

Answer

LAG gives the previous row's value within the partition, so the gap is a subtraction:

SQL
SELECT
  device_id, reading_at,
  reading_at - LAG(reading_at) OVER (PARTITION BY device_id ORDER BY reading_at) AS gap
FROM readings;

Wrapping that and filtering gap > interval '1 hour' finds the breaks. The filter has to be in an outer query, since the window result is not available to WHERE.

A detail worth being explicit about: the first row of each partition has no predecessor, so gap is NULL there. That is the honest answer, the first reading is not a gap, and I would keep it NULL rather than coalescing it to zero, which would assert something untrue.

For missing expected values rather than time gaps, the same idea applies to a sequence number: seq - LAG(seq) OVER (...) > 1 finds skipped identifiers. That is how I would detect dropped messages in an ordered stream.

The related and more interesting problem is grouping consecutive runs: 'find each continuous period a device was reporting'. The gaps-and-islands technique handles it: mark each row where a new run starts (gap > threshold, or the first row), take a running SUM of that marker to produce a run identifier, then group by it to get each run's start and end. Two window passes and a grouping, where the procedural alternative would be a cursor.

The caveats I would state. The partition must be right: comparing readings across devices would produce nonsense gaps. The ordering needs a tiebreaker if timestamps can collide, or 'previous' is ambiguous. And this finds gaps only between existing rows: a device that stopped reporting entirely has no final row to compare against, so detecting silence needs a comparison against the current time, or a left join onto the expected device list. A genuinely different query, and usually the one people actually needed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Describe the gaps-and-islands problem and how window functions solve it.

Answer

Gaps and islands is the problem of finding consecutive runs, islands, separated by breaks. Concretely: each continuous period a subscription was active, each streak of consecutive login days, each stretch a sensor reported without interruption.

It is awkward because 'consecutive' is a property of the relationship between adjacent rows, and SQL has no natural grouping key for it. The technique is to manufacture one.

Three steps. First, mark where each new island begins: compare each row to its predecessor with LAG and flag it when the difference exceeds the tolerance, or when there is no predecessor at all. Second, take a running SUM of that flag over the same ordering: every row in the same island gets the same total, because the total only increments at a boundary. That running total is the island identifier. Third, GROUP BY it to get each island's start, end and size.

SQL
WITH marked AS (
  SELECT *, CASE WHEN day - LAG(day) OVER (PARTITION BY user_id ORDER BY day) = 1
                 THEN 0 ELSE 1 END AS is_new_island
  FROM logins
),
islands AS (
  SELECT *, SUM(is_new_island) OVER (PARTITION BY user_id ORDER BY day
                                     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS island
  FROM marked
)
SELECT user_id, island, MIN(day) AS started, MAX(day) AS ended, COUNT(*) AS length
FROM islands GROUP BY user_id, island;

Note the explicit ROWS frame on the running sum: with the RANGE default and any tied ordering values, the island identifier would jump for tied peers together and merge islands that should be separate.

The alternative formulation for dense integer sequences is the difference between the value and its ROW_NUMBER: that difference is constant within a run, so it serves directly as the island key. It is shorter but only works when the expected step is exactly one and there are no duplicates.

The things I would confirm before writing either: what counts as a break. One missing day, or a tolerance; whether duplicates are possible, since they break the row-number variant and need deduplicating first; and whether islands should be bounded by the reporting window's edges, since a run that started before the window looks shorter than it is. That last one is the detail that most often makes streak reports disagree with what users see.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you use window functions to find each user's session boundaries from raw events?

Answer

Sessionisation is the gaps-and-islands pattern applied to time: a session is a run of events with no gap longer than an inactivity threshold.

Three steps. Use LAG to get the previous event's timestamp within the user's ordering. Mark a new session where the difference exceeds the threshold, or where there is no previous event. Take a running SUM of that marker to produce a session number, then group by it.

SQL
WITH gapped AS (
  SELECT *, occurred_at - LAG(occurred_at) OVER w AS gap
  FROM events
  WINDOW w AS (PARTITION BY user_id ORDER BY occurred_at, id)
),
marked AS (
  SELECT *, CASE WHEN gap IS NULL OR gap > interval '30 minutes' THEN 1 ELSE 0 END AS starts
  FROM gapped
),
sessions AS (
  SELECT *, SUM(starts) OVER (PARTITION BY user_id ORDER BY occurred_at, id
                              ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session_no
  FROM marked
)
SELECT user_id, session_no, MIN(occurred_at) AS started, MAX(occurred_at) AS ended,
       COUNT(*) AS events
FROM sessions GROUP BY user_id, session_no;

gap IS NULL handles each user's first event, which has no predecessor and must start a session. Forgetting it makes the first session of every user merge into session 0: a bug that shows up as a suspiciously large first session.

The explicit ROWS frame on the running sum is required: with the RANGE default and two events sharing a timestamp, the session number would advance for both peers together and merge sessions that should be distinct.

The tiebreaker id in the ordering matters for the same reason: simultaneous events otherwise make 'previous' ambiguous, and the session assignment nondeterministic.

The judgement calls are the interesting part. The threshold is a product decision, not a technical one, and 30 minutes is a convention rather than a fact: I would validate it against the actual distribution of inter-event gaps, which usually shows a clear bimodal split. Sessions spanning the query window's edges are truncated, so I would either extend the read window beyond the reporting window or exclude boundary sessions rather than report short ones. And a single-event session is legitimate but often uninteresting, so whether to keep it depends on what the metric is for.

At volume this is a natural incremental job: closed sessions never change, so only the trailing open ones need recomputation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Explain PERCENT_RANK, CUME_DIST and NTILE, and when each is appropriate.

Answer

All three are window functions that need an ORDER BY; they differ in what the number means. PERCENT_RANK and CUME_DIST report a position as a fraction in [0,1]; NTILE(n) assigns a bucket number. The distinction that decides most interviews: PERCENT_RANK is a normalized rank, not a population proportion, while CUME_DIST is the actual proportion of rows at or below the current row. All three are ranking functions, so the window frame clause is ignored: only ORDER BY matters.

Definitions, with n = rows in the partition:

  • PERCENT_RANK() = (RANK() - 1) / (n - 1). 0 for the first row, 1 for the last, 0 for a single-row partition.
  • CUME_DIST() = (rows preceding or tied with this row) / n. Range (0, 1]; minimum is 1/n, and 1 for the last row.
  • NTILE(n) splits the ordered partition into n buckets as evenly as it can; the remainder goes to the earlier buckets.

Trace over 8 applicants, ordered by score descending:

scoreRANKPERCENT_RANKCUME_DISTNTILE(4)
9010.00000.2501
9010.00000.2501
8530.28570.3752
8040.42860.7502
8040.42860.7503
8040.42860.7503
7070.85710.8754
6081.00001.0004

Read the score-70 row: PERCENT_RANK is 0.8571, but only 6 of 8 rows (75%) are strictly below it. So "scored better than 85% of applicants" is wrong if you got the 85 from PERCENT_RANK. CUME_DIST is 0.875, meaning 87.5% of the cohort scored at or below 70: that is the defensible phrasing. The two diverge because PERCENT_RANK divides by n-1 and excludes the current row, while CUME_DIST divides by n and includes the current row plus all its ties.

Ties: the three 80s share RANK 4, so they share PERCENT_RANK 0.4286 and CUME_DIST 0.75. Both are tie-aware; neither breaks ties.

NTILE remainder arithmetic: 10 rows into NTILE(4) gives bucket sizes 3, 3, 2, 2 (10 = 4×2 + 2, remainder to the first two buckets). 3 rows into NTILE(5) fills buckets 1–3 and leaves 4 and 5 empty.

Failure modes:

  • NTILE splits ties. In the trace the three 80s land in buckets 2, 3, 3, and which 80 goes to bucket 2 is arbitrary, because tied rows have no defined order. Two customers with identical spend can get different quartiles. If the bucket drives pricing or eligibility, that is indefensible.
  • PERCENT_RANK read as a percentile. It is not "percent of the cohort below"; it is a rank scaled to [0,1]. Reporting it as a percentile overstates by roughly one row's worth.
  • Single-row partition. PERCENT_RANK returns 0 and CUME_DIST returns 1. Both are degenerate; guard for n = 1 if the number feeds a decision.
  • NTILE(n) with n greater than the row count. Some buckets come back empty, so "quartile" labels stop being comparable across partitions of different sizes.

When each is appropriate:

  • CUME_DIST when you need "what fraction of the cohort is at or below this row": percentile reporting, threshold checks.
  • PERCENT_RANK when you need a rank normalized to [0,1] for scoring or blending, and you accept that it is not a population proportion.
  • NTILE when you need equal-sized cohorts and equal-value boundaries do not matter: A/B split, decile sampling, load balancing.
  • Neither when the boundary carries consequences. Use explicit thresholds (CASE WHEN score >= 90 THEN ...) or PERCENTILE_CONT/PERCENTILE_DISC so the cutoff is a stated value that can be inspected and defended.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

How would you compute a median (or an arbitrary percentile) per group using window functions?

Answer

Core. Pin down two things first: continuous or discrete percentile, and whether you need one row per group or the value sitting beside row-level columns. Then the answer splits.

PostgreSQL has the direct tool: percentile_cont(0.5) WITHIN GROUP (ORDER BY x) and percentile_disc(0.5) WITHIN GROUP (ORDER BY x). These are ordered-set aggregates, not window functions, and the window function reference says ordinary aggregates can be used with OVER, but ordered-set and hypothetical-set aggregates cannot. So percentile_cont(0.5) WITHIN GROUP (ORDER BY x) OVER (PARTITION BY g) is a syntax error. If one row per group is all you need, that is the whole answer:

sql SELECT g, percentile_cont(0.5) WITHIN GROUP (ORDER BY x) AS median FROM t GROUP BY g;

If you need the median next to row-level columns, either join that grouped result back, or build it from window functions, which is what the question asks, and what you need on engines without ordered-set aggregates.

Window construction. Rank inside the partition, count the partition, then average the middle one or two rows:

sql WITH ranked AS ( SELECT g, x, ROW_NUMBER() OVER (PARTITION BY g ORDER BY x) AS rn, COUNT(*) OVER (PARTITION BY g) AS n FROM t WHERE x IS NOT NULL ) SELECT g, AVG(x) AS median FROM ranked WHERE rn IN ((n + 1) / 2, (n + 2) / 2) GROUP BY g;

Integer division makes those two expressions collapse onto the same row for odd n and onto the two middle rows for even n. Trace:

x valuesrnn(n+1)/2(n+2)/2rows keptmedian
1,2,3,4,1001..553333
1,2,3,41..44232,32.5

Generalising to percentile p: discrete is rn = CEIL(p * n); continuous interpolates at 0-based position p * (n - 1), taking floor and ceil of that index and blending by the fractional part. The same definition percentile_cont uses. In the CTE shape above that means pulling the two rows with MAX(x) FILTER (WHERE i = floor(...)) and MAX(x) FILTER (WHERE i = ceil(...)) and combining them.

Failure modes. NULLs are the classic one: COUNT(*) counts them and the window's default NULLS LAST pushes them to the top ranks, so n is inflated and the middle rows shift. Filter them out or use COUNT(x). Ties are harmless here: unlike top-N, tied rows carry equal values, so which one ROW_NUMBER picks cannot change the result. Precision: percentile_cont over double precision is approximate, over numeric it is exact, and AVG of two integers returns numeric in PostgreSQL. Cost: the window needs its input ordered by (g, x), so it is O(n log n) per partition and materialises the partition; an index on (g, x) can let the planner skip the Sort node, but check the plan rather than assuming. For a group with tens of millions of rows, an exact median means sorting all of them: sampling or a sketch is the escape hatch.

When not to. If you need one row per group, the ordered-set aggregate is a single pass and beats the CTE. Reach for the window version when the percentile must sit beside row-level columns, when you want several percentiles in one pass, or on an engine without ordered-set aggregates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How would you build a cohort retention report using window functions?

Answer

Retention needs each user assigned to a cohort by their first activity, then activity measured in periods relative to that cohort, not in absolute calendar time.

The window does the cohort assignment: MIN(activity_month) OVER (PARTITION BY user_id) gives every one of a user's rows their cohort month without a self-join or a separate aggregation pass. Then the period offset is the difference between the activity month and the cohort month, and the report is a count of distinct users grouped by cohort and offset.

SQL
WITH activity AS (
  SELECT user_id, DATE_TRUNC('month', occurred_at) AS month FROM events GROUP BY 1, 2
),
cohorted AS (
  SELECT user_id, month, MIN(month) OVER (PARTITION BY user_id) AS cohort FROM activity
)
SELECT cohort,
       (EXTRACT(YEAR FROM month) - EXTRACT(YEAR FROM cohort)) * 12
         + (EXTRACT(MONTH FROM month) - EXTRACT(MONTH FROM cohort)) AS period,
       COUNT(DISTINCT user_id) AS retained
FROM cohorted GROUP BY cohort, period ORDER BY cohort, period;

The distinct count matters because a user active many times in a month must count once. The inner grouping to one row per user-month already handles that, which is why it is there rather than relying on DISTINCT later.

The judgement calls that decide whether the report is trustworthy are not the SQL. Period 0 is always 100% by construction, if it is not, the cohort assignment is wrong, so it is a useful self-check rather than a finding. Incomplete periods must be excluded or marked: the current month is partial, so its retention is always artificially low and reads as a cliff. The activity definition matters more than anything: 'logged in' and 'performed a meaningful action' give very different curves, and the definition belongs in the report's labelling, not just the code. The cohort must be bounded by available history: users whose first activity predates the data window get assigned a false cohort, so I exclude cohorts that cannot be complete rather than showing a misleading one.

At scale I would precompute this rather than run it per view: it aggregates all history every time, and the older cohorts never change, so it is a natural incremental rollup.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How does filtering interact with window functions, and what mistakes does that cause?

Answer

Filtering interacts with windows in three distinct places, and confusing them is the most common source of subtly wrong window queries.

WHERE, before the window. It removes rows from the window's input entirely. A running total with WHERE status = 'paid' totals only paid orders: the unpaid ones are not hidden from the output, they are absent from the calculation. Usually intended, but it must be a decision, because 'running total of paid orders' and 'running total of all orders, showing only paid rows' are different reports and the second cannot be written this way at all.

An outer query, after the window. This is the only place a window result can be filtered, since WHERE and HAVING both precede the SELECT phase. It is why top-N-per-group is nested. Critically, filtering here does not change the window: rank 4 was computed knowing about ranks 1 to 3, and discarding it afterwards leaves the remaining ranks correct.

FILTER (WHERE ...) on the aggregate itself. This scopes one aggregate's input without removing any rows or affecting the other functions, so one pass can produce a running total of everything alongside a running total of just the refunds.

The mistake I see most is using WHERE when the third was meant: filtering the query down to one category to compute a percentage, then finding every percentage is 100% because the window's total now covers only that category. The fix is PARTITION BY or FILTER, not WHERE.

The second most common is the reverse: filtering in the outer query and expecting the ranking to renumber. It will not, and should not: if you want ranks 1, 2, 3 among the survivors, the filter belongs before the window.

So the question I ask of any filter near a window is: should this change what the window sees, or only what the reader sees? The answer picks the placement, and it is worth writing down in a comment, because the next person will wonder.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How do window functions behave with GROUP BY in the same query?

Answer

They compose, and the key is that windows are evaluated after grouping. So in a grouped query, the window's input rows are the grouped rows, one per grouping key, not the original table rows.

That has an immediate practical consequence: everything inside the window expression must be valid in a grouped context. You cannot reference a bare ungrouped column, but you can wrap an aggregate: SUM(SUM(amount)) OVER (PARTITION BY region) is legal and means 'sum, across the grouped rows, of each group's summed amount'. The inner aggregate collapses within the group; the outer window operates across groups.

The partition inside OVER then partitions grouped rows. Grouping by region and product and partitioning by region gives each product row its region's total: the standard percentage-of-parent shape, in one pass.

Similarly, ranking after grouping ranks the groups: RANK() OVER (ORDER BY SUM(amount) DESC) in a query grouped by product ranks products by their totals. Trying to rank the raw rows in the same query is impossible, because those rows no longer exist by the time the window runs.

The error people hit is expecting the window to see pre-aggregation detail: computing a running total of individual orders in a query grouped by month. It cannot: the orders were collapsed before the window existed. That needs two levels, with the ungrouped detail in an inner query.

And the ordering rule holds throughout: HAVING still runs before the window, so it filters groups on aggregate values; filtering on the window result still requires an enclosing query. A query that groups, filters groups with HAVING, ranks the survivors with a window, and then keeps the top three needs both HAVING and an outer WHERE, which reads oddly until the evaluation order makes it obvious.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

When would you use a window function instead of a self-join, and when not?

Answer

Default to the window function when the relationship is within a partition and what you need is a computed value over the related rows. Reach for the join when you need the related rows' columns, when the relationship crosses tables, or when the match isn't an ordering.

Why the window usually wins. A self-join for a group total scans the table twice and joins it to an aggregated copy of itself. The window does it in one pass.

SQL
-- orders(order_id, customer_id, seq, amount)
-- (1,7,1,10) (2,7,2,20) (3,7,5,30)

SELECT o.order_id, o.amount, SUM(o2.amount) AS customer_total
FROM orders o JOIN orders o2 ON o2.customer_id = o.customer_id
GROUP BY o.order_id, o.amount;
-- intermediate: 3 x 3 = 9 rows for customer 7
-- output: (1,10,60) (2,20,60) (3,30,60)

SELECT order_id, amount, SUM(amount) OVER (PARTITION BY customer_id) AS customer_total
FROM orders;
-- 3 rows in, 3 rows out, same totals

Previous-row comparison is where the join breaks, not just slows. p.seq = o.seq - 1 assumes dense sequence numbers. With the rows above, order 3 has seq 5, so the join finds no predecessor and returns NULL. LAG is defined by position in the ordering:

SQL
SELECT order_id, amount,
       LAG(amount) OVER (PARTITION BY customer_id ORDER BY seq) AS prev_amount
FROM orders;
-- (1,10,NULL) (2,20,10) (3,30,20)

Fan-out. A self-join that matches more than once per row duplicates it, and any aggregate computed afterwards is inflated silently: no error, just a bigger number. A window returns exactly one value per input row by construction, so that class of bug can't happen.

Cost, with numbers. Hypothetical: 1M orders, 200k customers, 5 orders each. The self-join's intermediate is 200k × 5² = 5M rows before the GROUP BY. At 20 orders per customer it is 200k × 400 = 80M. The window scans 1M rows once and sorts by customer_id. The gap widens with the square of the group size.

When the join is right.

  • You need columns, not a value. The previous order's status, shipping address and notes means five LAG calls; one join returns all of them. LATERAL is the middle ground.
  • The related rows live in another table.
  • The match isn't an ordering: nearest by distance, range overlap, fuzzy key.
  • You want to filter on the result. Window functions aren't allowed in WHERE, so ROW_NUMBER() ... = 1 needs a subquery or CTE, and the sort still touches every row in the partition. If the filter is selective and the join key is indexed, an indexed self-join can stop early and win.

Portability. Window functions are in every mainstream engine. Frame support is not uniform: PostgreSQL 11+ has GROUPS, MySQL 8.0 and SQL Server do not. If the query must run on several engines, check the frame mode before committing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

When is a window function the wrong tool, and what would you use instead?

Answer

Windows are the right default for row-relative calculations, but there are cases where reaching for one makes things worse.

When the rows should genuinely collapse. If the output is one row per group, GROUP BY says so directly. Using a window and then DISTINCT to collapse it computes over every row and then deduplicates the result: more work, and the DISTINCT obscures the intent.

When a plain aggregate suffices. MIN(created_at) grouped by customer beats FIRST_VALUE with a full frame and a DISTINCT if the date is all that is needed.

When you need many columns from a related row. LAG returns one expression per call, so pulling six columns from the previous order means six LAG calls that must all carry identical OVER clauses. A self-join or a lateral join reads far better and is less prone to one clause drifting from the others.

When the relationship is not an ordering. Matching to the nearest row by some non-sequential distance, or to a row in another table on a range condition, is a join: possibly a lateral one. Windows only see rows in the same partition, ordered.

When the calculation is genuinely recursive. A value depending on the previous row's computed result, compound balances where each row's output feeds the next, is not expressible as a window, because windows read input values, not their own prior outputs. That needs a recursive CTE.

When the data volume makes the required sort untenable and the query runs constantly. At that point precomputing into a rollup beats optimising the window.

The general principle: windows are for computing a value from a set of input rows related to the current one. When the requirement is to reshape rows, to reach across a relationship that is not an ordering, or to feed a computation back into itself, something else fits better.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What determinism problems can window functions introduce into a report?

Answer

Windows introduce a second ordering, the one inside OVER, and it needs the same determinism discipline as the query's final ORDER BY, but it is far more often forgotten because it does not affect how the output looks.

Ties in the window's ORDER BY. ROW_NUMBER over a non-unique ordering assigns numbers arbitrarily among tied rows, so a top-N cutoff can return different rows between identical runs. This is the big one, and it produces intermittent bugs that nobody can reproduce on demand. The fix is a unique tiebreaker, normally the primary key.

ROWS with tied ordering. Even with the correct positional frame, the accumulation order among tied rows is arbitrary, so intermediate running-total values differ between runs even though the final total does not. If those intermediates are displayed, they need the tiebreaker too.

NULL placement. Whether NULLs sort first or last changes who ranks top and where offsets land. If the engine default is relied upon rather than stated, a configuration or engine change silently reorders the report.

NTILE remainder distribution. When rows do not divide evenly, extra rows go to earlier buckets, so adding one row can move an unrelated customer across a bucket boundary. Reproducible for fixed input, but not stable as data grows, which surprises people when a quartile changes without that customer changing.

Floating-point aggregates in windows. Running SUM over a float column depends on summation order, so a changed plan changes the intermediate values. Exact numerics remove this.

For a report that must be reproducible I fix all of them: a unique tiebreaker in every window ORDER BY, explicit frames, explicit NULLS FIRST/LAST, exact numerics, and parameters rather than now() for any date bound. Then I would validate by running it twice and diffing: cheap, and it catches exactly this class of defect before a stakeholder does.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do window functions perform, and what can you do about a slow one?

Answer

The 90-second answer

A window function is a sort followed by a streaming pass. The planner sorts the input by (partition keys, order keys), then a WindowAgg node walks the sorted rows once per window definition. The sort dominates: O(n log n) comparisons, and, more importantly, it is bounded by work_mem (default 4 MB), so a large input spills to disk. The WindowAgg pass itself is usually linear and cheap.

So the first move is always the same: read EXPLAIN (ANALYZE, BUFFERS) and look at the Sort node. Sort Method: quicksort Memory: 812kB is fine. Sort Method: external merge Disk: 412000kB is the cliff behind most "fine in staging, slow in production" window queries.

What the plan looks like (illustrative, 20M-row orders table)

WindowAgg  (cost=... rows=20000000 width=48) (actual time=... rows=20000000 loops=1)
  ->  Sort  (cost=... rows=20000000 width=48) (actual time=18422.6..21003.1 rows=20000000 loops=1)
        Sort Key: customer_id, created_at DESC, id DESC
        Sort Method: external merge  Disk: 412000kB
        ->  Seq Scan on orders  (...)

412 MB of spill for a 20M-row input. That is the number to attack.

Arithmetic. 20M rows × ~120 bytes of sort tuple ≈ 2.4 GB. At 4 MB of work_mem per sort, each in-memory run holds ~35k rows, so the sort produces ~570 runs and the merge reads 2.4 GB back. Raising work_mem to 256 MB cuts that to ~10 runs. It does not remove the sort.

Levers, in the order I would try them

  1. Index on the exact sort key: (customer_id, created_at DESC, id DESC). If the planner can read rows in that order, the Sort disappears. PostgreSQL 13+ can also use Incremental Sort to exploit an index matching only a prefix of the key.

  2. Make identical windows identical. Functions sharing one OVER are computed in a single WindowAgg pass over one sort. A named WINDOW w AS (PARTITION BY customer_id ORDER BY created_at DESC, id DESC) guarantees that as the query is edited. Different partition or order keys force another sort; a different frame costs another WindowAgg pass but not necessarily another sort, because the sort is keyed on partition and order keys only.

  3. Filter before the window. WHERE runs before WindowAgg, so shrinking the input shrinks the sort proportionally.

  4. Top-N per partition: do not rank everything. ROW_NUMBER() ... WHERE rn <= 3 still sorts all 20M rows. A lateral join with a matching index reads 3 rows per customer instead:

SQL
SELECT c.id, o.*
FROM customers c
CROSS JOIN LATERAL (
  SELECT * FROM orders o
  WHERE o.customer_id = c.id
  ORDER BY o.created_at DESC, o.id DESC
  LIMIT 3
) o;

That is an index scan per customer, no global sort.

  1. work_mem, scoped to the query, SET LOCAL work_mem = '256MB', once the plan confirms a spill.

Failure modes

  • Spill: external merge Disk: in the plan.
  • Misestimate: compare estimated vs actual rows on the Sort's child. If the planner expected 50k and got 20M, it may have picked a nested loop that is wrong for the real data; ANALYZE can fix it with no query change.
  • Skew: one partition with 10M rows and the rest with 10. The sort is fine but that one WindowAgg pass dominates. Check with SELECT customer_id, count(*) FROM orders GROUP BY 1 ORDER BY 2 DESC LIMIT 10.
  • Buffering: RANGE frames must see the whole peer group before emitting, so they buffer; ROWS frames ending at CURRENT ROW with UNBOUNDED PRECEDING can stream. NTILE and frames ending at UNBOUNDED FOLLOWING buffer the partition.

When not to tune it

If a dashboard recomputes the same window over slow-changing data on every request, precompute it, a rollup table or materialized view refreshed on a schedule, rather than tuning a query that should not run per request.

Curated: · Written: · Reviewed:

Difficulty: Hard