Skip to content

Lesson 8 of 13 · 15m

Window Functions Without the Self-Joins

Window functions keep every row while ranking it inside its partition — the dedup, running-total, and latest-per-key patterns that end self-joins.

Every "latest row per group" query you've ever written as a self-join — SELECT o.* FROM orders o JOIN (SELECT customer_id, max(created_at) m FROM orders GROUP BY customer_id) x ON ... — exists because GROUP BY collapses rows and you needed the rows back. Window functions exist to end that pattern. ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) labels each row with its rank inside its own group without collapsing anything: every input row comes out, carrying a new column that knows where it sits relative to its partition-mates.

The wrong model: GROUP BY is how you aggregate

GROUP BY is how you summarize — it folds a group into one output row and everything you didn't aggregate disappears. Window functions compute the same aggregates but keep every row. SUM(total) OVER (PARTITION BY customer_id) is the customer's lifetime spend stamped onto each of their orders. SUM(total) OVER (PARTITION BY customer_id ORDER BY created_at ROWS UNBOUNDED PRECEDING) is the running total — cumulative spend as of that order — a report that takes a correlated subquery or a join to compute any other way.

The frame clause is where the real power lives. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is the default when ORDER BY is inside the OVER. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is a 7-row moving average. RANGE BETWEEN groups by value-distance instead of row-distance (RANGE BETWEEN interval '1 hour' PRECEDING AND CURRENT ROW on a timestamp). And GROUPS mode handles peer sets. Most people never write a frame clause and never realize the default they got.

The dedup pattern that pays rent

DELETE FROM events e
USING (
  SELECT ctid, ROW_NUMBER() OVER (PARTITION BY dedup_key ORDER BY created_at DESC) rn
  FROM events
) ranked
WHERE e.ctid = ranked.ctid AND ranked.rn > 1;

Keep the newest row per dedup_key, delete the rest, one statement. The pre-window version of this — DELETE WHERE id NOT IN (SELECT max(id) ...) — computes the max per group then compares every row against it; on big tables it runs for hours and locks while it does. The window version is one pass.

For the read side, Postgres has DISTINCT ON: SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC returns the newest order per customer in one line — Postgres-specific, faster than the portable ROW_NUMBER() = 1 subquery for exactly this shape.

ROW_NUMBER vs RANK vs DENSE_RANK — the ties

ROW_NUMBER invents a total order: ties get 1, 2, 3 arbitrarily. RANK gives ties the same rank then skips — 1, 1, 3. DENSE_RANK gives ties the same rank without skipping — 1, 1, 2. Pick wrong and a leaderboard either drops people or double-awards prizes. For dedup you always want ROW_NUMBER — exactly one survivor. For "top 3 scores" you want DENSE_RANK or RANK depending on whether ties should consume slots.

LAG/LEAD reach the previous/next row in the window: LAG(total) OVER (PARTITION BY customer ORDER BY created_at) is the prior order's value — deltas, session gaps, "did this metric regress" without a self-join. FIRST_VALUE/LAST_VALUE grab partition endpoints (mind the frame — LAST_VALUE under the default frame returns the current row; you want ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING).

The placement rules that bite

Window functions are evaluated after WHERE and GROUP BY — the window sees the post-filter row set. Consequences: you can't put a window call inside WHERE (wrap it in a subquery and filter outside — WHERE rn = 1), you can't nest a window inside a window, and an aggregate inside OVER aggregates the post-GROUP BY rows if you mix them. Also: OVER () with no PARTITION BY is one giant window over everything — legal and occasionally what you want (total-share-of-everything reports), but it sorts the entire result if you add ORDER BY inside.

What to actually do

  • Latest-per-key reads: DISTINCT ON on Postgres; ROW_NUMBER() = 1 everywhere else.
  • Dedup deletes: window rn > 1 with ctid, never NOT IN (SELECT max...).
  • Running totals, moving averages, deltas: frame clause plus LAG, no self-joins.
  • Leaderboards with ties: RANK/DENSE_RANK, chosen by whether ties consume slots.
  • Filtering on a window result: subquery or CTE, filter on the outside.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.