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 ONon Postgres;ROW_NUMBER() = 1everywhere else. - Dedup deletes: window
rn > 1withctid, neverNOT 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?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
PHP API Performance: N+1 Queries, cURL, and Connection Pools
A PHP API case study: fixing an N+1 query, twenty serial cURL calls, missing connection pooling, and stats recalculated on every request with Redis caching.