Aggregation, window functions, CTEs
GROUP BY collapses rows, windows keep them: top-N per group, running totals and gaps-and-islands, and the EXPLAIN that shows when a window beats a self-join
A table has three rows for 1 May with amounts 10, 20 and 30, and one row for 2 May with amount 5. You run SELECT day, amount, sum(amount) OVER (ORDER BY day) FROM t. What running totals do the three 1 May rows show?
The previous chapter combined relations. This one summarises them. There are two ways to compute across rows in SQL, and they differ in one thing: whether the rows survive. GROUP BY collapses each group into one row. A window function computes the same kind of value but leaves every input row in place and attaches the result as a column. Most reporting questions are one or the other, and the expensive mistakes come from forcing one into the shape of the other: a self-join to fake a window, or a GROUP BY followed by a join back to the detail rows.
The third tool is the common table expression, WITH, which names an intermediate result so a query reads top to bottom. Its recursive form walks hierarchies and generates series. Together these three cover top-N per group, running totals, period-over-period comparison and gaps-and-islands, which between them are most of the analytical SQL you will write.
GROUP BY and HAVING
GROUP BY partitions the rows that survive WHERE into groups with equal values in the grouping columns, then evaluates each aggregate once per group. The output has one row per group. Every column in SELECT must either be in the GROUP BY list or be inside an aggregate, with one Postgres exception: if you group by a table’s primary key, you may select any other column of that table, because the key functionally determines it.
The aggregates you use most are count, sum, avg, min, max, plus count(DISTINCT x), string_agg, array_agg and the ordered-set aggregates percentile_cont(0.5) WITHIN GROUP (ORDER BY x) for a median. Remember from the previous chapter that every aggregate except count(*) ignores NULLs, and that sum over zero rows returns NULL, not 0; coalesce(sum(x), 0) is the defensive form.
HAVING filters groups after they are formed. It is the only place you can test an aggregate: HAVING count(*) > 10. A condition on a plain column can go in either WHERE or HAVING and gives the same result, but in WHERE it removes rows before they are aggregated, so put it there.
FILTER is the clause that removes most CASE expressions from reports. count(*) FILTER (WHERE status = 'cancelled') counts cancelled orders in the same pass as count(*). One scan, several conditional aggregates, no subqueries.
GROUPING SETS, ROLLUP and CUBE produce several groupings in one query. GROUP BY ROLLUP (country, status) gives rows per country and status, a subtotal per country, and a grand total, with NULL in the rolled-up columns; grouping(status) tells a real NULL from a subtotal marker. It is one sort instead of three queries glued with UNION ALL.
Window functions
A window function call is a function followed by OVER (...). The parentheses define, for each row, which other rows the function sees:
fn(args) OVER (
PARTITION BY ... -- split rows into independent groups (like GROUP BY, but rows are kept)
ORDER BY ... -- order within each partition
frame -- which rows around the current one: ROWS / RANGE / GROUPS BETWEEN ...
)
Windows are evaluated after WHERE, GROUP BY and HAVING, and before the final ORDER BY and LIMIT. Two consequences. You can window over aggregates (rank() OVER (ORDER BY sum(total_cents) DESC) in a grouped query). And you cannot filter on a window result in WHERE of the same query: you wrap it in a subquery or CTE and filter outside. Every top-N-per-group query has that shape.
The family splits in three:
| kind | functions | needs ORDER BY | uses the frame |
|---|---|---|---|
| ranking | row_number, rank, dense_rank, percent_rank, cume_dist, ntile(n) |
yes | no |
| offset | lag(x, n, default), lead(x, n, default) |
yes | no |
| frame | first_value, last_value, nth_value, and every ordinary aggregate (sum, avg, count, min, max) |
optional | yes |
Ranking. row_number() numbers rows 1, 2, 3 with no ties, so the order among equal rows is arbitrary unless the ORDER BY is unique. rank() gives equal rows the same number and leaves a gap after them; dense_rank() gives equal rows the same number and leaves no gap. For “the latest order per customer” you want row_number() with a tie-breaker. For “every product in its category’s top three by revenue, including ties” you want rank() or dense_rank().
Offset. lag(created_at) OVER (PARTITION BY customer_id ORDER BY created_at) is the previous order’s timestamp for the same customer, NULL for their first. lead looks forward. Both take an offset and a default. They replace the correlated subquery in the Why.
Frames. The frame is the set of rows, relative to the current one, that a frame function sees. The default depends on whether ORDER BY is present. Without it, the frame is the whole partition, so sum(x) OVER (PARTITION BY customer_id) is the customer’s total on every row. With it, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which is a running total, with the peer behaviour the Predict showed.
Three frame modes exist. ROWS counts physical rows: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is the last seven rows. RANGE works in values of the ORDER BY column: RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW is every row within the last seven days by date, however many there are, which is what a 7-day moving average over days with missing data needs. GROUPS counts peer groups. Postgres also supports EXCLUDE CURRENT ROW, EXCLUDE GROUP and EXCLUDE TIES to remove rows from the frame.
last_value is the classic frame trap. last_value(x) OVER (ORDER BY day) returns the current row’s value, because the default frame ends at the current row. Write ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING when you mean the partition’s last row.
A named window reuses one definition across columns, which also lets Postgres compute them from one sort:
SELECT id, created_at,
row_number() OVER w AS n,
lag(created_at) OVER w AS prev_at
FROM orders
WHERE customer_id = 42
WINDOW w AS (PARTITION BY customer_id ORDER BY created_at, id);
How a window executes
The executor node is WindowAgg. Its input must be sorted by the partition keys and then the order keys, so the plan below it is a Sort (or an index that provides the order). WindowAgg then walks the sorted rows once, keeping as much of the frame in memory as it needs: nothing extra for row_number, one row of history for lag, a running accumulator for a ROWS ... UNBOUNDED PRECEDING sum. Several windows with the same PARTITION BY and ORDER BY share one sort; a different order means another sort and another WindowAgg.
So a window over two million orders costs one sort of two million rows, which with work_mem at its default of 4 MB spills to disk and takes a few seconds on a laptop. Raising work_mem for the session (SET work_mem = '256MB') usually keeps it in memory. An index on (customer_id, created_at) lets the planner skip the sort altogether; the indexes chapter adds it.
Windows against self-joins
Before windows, “previous order per customer” was a self-join or a correlated subquery:
SELECT o.id, o.created_at,
(SELECT max(p.created_at) FROM orders p
WHERE p.customer_id = o.customer_id AND p.created_at < o.created_at) AS prev_at
FROM orders o;
Without an index on customer_id, the subquery is a sequential scan of two million rows for each of two million outer rows: four trillion row visits, which never finishes. With an index it becomes an index probe per row, two million random lookups, and finishes in seconds to minutes depending on cache. The window version sorts once and walks once. The lab puts both through EXPLAIN (ANALYZE, BUFFERS) on one country so you can see the shape and the buffer counts side by side.
The rule: when the question is “for each row, something about its neighbours in some order”, it is a window. A self-join is right when the relationship is not an ordering, such as pairs of customers in the same country, or when you need rows that the window’s partition would not contain.
CTEs
WITH name AS (query) names a result for the rest of the statement. It is mainly a readability tool: a revenue report becomes a sequence of named steps, each checkable on its own, instead of three nested subqueries read inside out. You can also run a CTE on its own while debugging, which is the most useful property of all.
Performance changed in Postgres 12. Before it, every CTE was an optimisation fence, computed once and materialised. Since 12, a non-recursive CTE without side effects that is referenced once is inlined into the main query, so the planner can push filters into it. A CTE referenced more than once is still materialised by default. You override either way with WITH x AS MATERIALIZED (...) or AS NOT MATERIALIZED (...). If you learnt “CTEs are slow in Postgres”, it was true before 2019.
Data-modifying CTEs are a Postgres feature you will use in later chapters: WITH moved AS (DELETE FROM orders WHERE ... RETURNING *) INSERT INTO orders_archive SELECT * FROM moved moves rows in one statement and one snapshot.
Recursive CTEs
WITH RECURSIVE has a non-recursive term, UNION or UNION ALL, and a recursive term that references the CTE’s own name. Postgres evaluates the first term, then repeatedly evaluates the recursive term against only the rows produced in the previous iteration, stopping when an iteration produces nothing. It is iteration, not recursion, despite the name.
Two uses matter. Walking a hierarchy: a category tree stored as (id, parent_id) is expanded into every descendant of a node. And generating rows: a calendar of every day in a range, although Postgres’s generate_series(date '2024-01-01', date '2024-12-31', interval '1 day') does that one more directly. Postgres 14 added SEARCH DEPTH FIRST BY / SEARCH BREADTH FIRST BY for ordering and CYCLE ... SET ... USING for detecting loops; a recursive CTE over data with a cycle and UNION ALL never terminates without one.
Patterns
Top-N per group. Rank inside a CTE, filter outside:
WITH ranked AS (
SELECT p.category, p.id, p.name, sum(oi.qty * oi.unit_price_cents) AS revenue,
rank() OVER (PARTITION BY p.category ORDER BY sum(oi.qty * oi.unit_price_cents) DESC) AS r
FROM order_items oi JOIN products p ON p.id = oi.product_id
GROUP BY p.category, p.id, p.name
)
SELECT * FROM ranked WHERE r <= 3 ORDER BY category, r;
The alternative is LATERAL: for each category, a subquery with ORDER BY ... LIMIT 3. With an index that provides the order it reads three rows per group instead of all of them, so it wins when groups are large and an index exists; the window wins when you need to read everything anyway, as for an aggregate.
Running totals. sum(x) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) over a per-day aggregate. Aggregate to one row per day first, then window; windowing over two million orders and then grouping does the work twice.
Period over period. lag(revenue, 7) OVER (ORDER BY day) is the revenue a week ago on a daily series with no gaps. With gaps, lag counts rows, not days, and the answer is wrong. Fill the gaps by left-joining to generate_series first.
Gaps and islands. “Find each customer’s streaks of consecutive days with an order.” Within a run of consecutive dates, the date minus its row number within the partition is constant; when a day is skipped, the difference jumps. That constant is a group key:
WITH days AS (
SELECT DISTINCT customer_id, created_at::date AS d FROM orders WHERE customer_id = 42
), tagged AS (
SELECT customer_id, d, d - (row_number() OVER (PARTITION BY customer_id ORDER BY d))::int AS island
FROM days
)
SELECT customer_id, min(d) AS start_day, max(d) AS end_day, count(*) AS days
FROM tagged GROUP BY customer_id, island ORDER BY start_day;
The DISTINCT matters: two orders on one day would get two row numbers and split the island. Subtracting an integer from a date in Postgres gives a date, which makes the island key a date too.
All queries are read-only. The shop’s orders run from 2023-11-01 to 2026-11-01, so the date windows below are fixed to the end of the data rather than to now(). Open psql and turn timing on.
cd labs/databases && docker compose exec db psql -U atlas shop\timing on1. GROUP BY, HAVING and FILTER. Orders per status per country, for countries with more than 50 000 orders.
SELECT c.country,
count(*) AS orders,
count(*) FILTER (WHERE o.status = 'cancelled') AS cancelled,
round(100.0 * count(*) FILTER (WHERE o.status = 'cancelled') / count(*), 2) AS cancel_pct
FROM orders o JOIN customers c ON c.id = o.customer_id
GROUP BY c.country
HAVING count(*) > 50000
ORDER BY orders DESC;HAVING count(*) > 5000 for the same five. One scan of orders, one hash join, one HashAggregate. Move count(*) > 50000 into WHERE and read the error: aggregate functions are not allowed in WHERE.2. ROLLUP.
SELECT country, status, count(*), grouping(status) AS is_subtotal
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE c.country IN ('DE', 'GB')
GROUP BY ROLLUP (country, status)
ORDER BY country NULLS LAST, status NULLS LAST;status NULL and is_subtotal 1, and a grand total with both NULL. One query instead of three.3. Ranking functions side by side.
SELECT category, price_cents,
row_number() OVER w, rank() OVER w, dense_rank() OVER w
FROM products
WHERE category = (SELECT min(category) FROM products)
WINDOW w AS (ORDER BY price_cents DESC)
LIMIT 15;row_number keeps counting, rank repeats then skips, dense_rank repeats and does not skip. If no prices tie in the first 15, change the window to ORDER BY price_cents / 1000 DESC to create ties.4. Top three products by revenue per category.
SET work_mem = '256MB';
WITH rev AS (
SELECT product_id, sum(qty * unit_price_cents) AS revenue FROM order_items GROUP BY product_id
), ranked AS (
SELECT p.category, p.name, r.revenue,
rank() OVER (PARTITION BY p.category ORDER BY r.revenue DESC) AS rk
FROM rev r JOIN products p ON p.id = r.product_id
)
SELECT category, rk, name, revenue / 100 AS euros FROM ranked WHERE rk <= 3 ORDER BY category, rk;5. Daily revenue and a running total.
WITH daily AS (
SELECT created_at::date AS day, sum(total_cents) AS cents
FROM orders WHERE created_at >= TIMESTAMPTZ '2026-11-01' - interval '90 days' AND status <> 'cancelled'
GROUP BY 1
)
SELECT day, cents / 100 AS euros,
sum(cents) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) / 100 AS running,
round(avg(cents) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) / 100) AS avg_7d
FROM daily ORDER BY day;running grows monotonically and its last value equals the 90-day total. avg_7d is smoother than euros. The first six rows average fewer than seven days because the frame is truncated at the start; that is correct, and a chart that hides it is lying slightly.6. The peer trap. Run the running total over orders, not days, with the default frame.
SELECT created_at::date AS day, total_cents,
sum(total_cents) OVER (ORDER BY created_at::date) AS range_default,
sum(total_cents) OVER (ORDER BY created_at::date, id ROWS UNBOUNDED PRECEDING) AS rows_frame
FROM orders WHERE customer_id IN (SELECT id FROM customers ORDER BY id LIMIT 50)
ORDER BY created_at::date, id LIMIT 20;range_default shows the same value on both rows, already including both; rows_frame steps through them one at a time. This is the Predict, on real data.7. LAG: days between orders.
SELECT customer_id, id, created_at,
created_at - lag(created_at) OVER (PARTITION BY customer_id ORDER BY created_at, id) AS since_prev
FROM orders WHERE customer_id <= 20
ORDER BY customer_id, created_at;WHERE it sorts two million rows once and completes in a few seconds.8. Window against self-join, with EXPLAIN evidence. Restrict to one country so the self-join finishes.
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, lag(o.created_at) OVER (PARTITION BY o.customer_id ORDER BY o.created_at, o.id) AS prev_at
FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.country = 'JP';
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, (SELECT max(p.created_at) FROM orders p
WHERE p.customer_id = o.customer_id AND p.created_at < o.created_at) AS prev_at
FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.country = 'JP'
LIMIT 200;Gather Merge), with the orders table read once (shared hit/read about 24 000 buffers at scale 1, 2 400 at 0.1) and a total time well under a second. The subquery plan shows a SubPlan with loops=200 and a Seq Scan on orders p inside it: each of only 200 outer rows scans the whole orders table, so buffers are in the millions and the time is far higher than the window’s for every row, even with the LIMIT. Drop the LIMIT and it would run for hours. The window is one sort; the correlated subquery is a scan per row.9. Gaps and islands on order dates. Find the customer with the longest streak of consecutive order days among the heavy buyers.
WITH heavy AS (
SELECT customer_id FROM orders GROUP BY customer_id ORDER BY count(*) DESC LIMIT 1000
), days AS (
SELECT DISTINCT o.customer_id, o.created_at::date AS d
FROM orders o JOIN heavy h USING (customer_id)
), tagged AS (
SELECT customer_id, d, d - (row_number() OVER (PARTITION BY customer_id ORDER BY d))::int AS island
FROM days
)
SELECT customer_id, min(d) AS start_day, max(d) AS end_day, count(*) AS streak_days
FROM tagged GROUP BY customer_id, island
ORDER BY streak_days DESC, customer_id LIMIT 5;end_day - start_day + 1 = streak_days. Check that equation: it is the proof the island key works. With the loader’s distribution the longest streaks are a few days; a real shop’s loyalty team asks this question about subscriptions.10. A recursive CTE: fill the calendar, then compare week on week.
WITH RECURSIVE cal(day) AS (
SELECT DATE '2026-10-31' - 60
UNION ALL
SELECT day + 1 FROM cal WHERE day < DATE '2026-10-31'
), daily AS (
SELECT cal.day, coalesce(sum(o.total_cents), 0) AS cents
FROM cal LEFT JOIN orders o ON o.created_at >= cal.day AND o.created_at < cal.day + 1
GROUP BY cal.day
)
SELECT day, cents / 100 AS euros, lag(cents, 7) OVER (ORDER BY day) / 100 AS same_day_last_week
FROM daily ORDER BY day DESC LIMIT 10;lag(cents, 7) really is seven days back; on the ungapped daily from step 5 it would only be seven rows back. generate_series does the calendar in one call; the recursive form is here so that you have written one.lag(cents, 7) OVER (ORDER BY day) to work on a version of daily built from orders only (drop the cal join and use GROUP BY o.created_at::date), then delete every order on one recent day inside a transaction: BEGIN; DELETE FROM payments WHERE order_id IN (SELECT id FROM orders WHERE created_at::date = DATE '2026-10-28'); DELETE FROM order_items WHERE order_id IN (SELECT id FROM orders WHERE created_at::date = DATE '2026-10-28'); DELETE FROM orders WHERE created_at::date = DATE '2026-10-28'; and re-run before ROLLBACK;. Every comparison after the missing day now looks eight days back, not seven, and nothing in the output says so. LAG counts rows. A week-on-week chart built that way drifts the first time a day has no sales.An API endpoint returns each of a customer's last three orders on a profile page, called about 200 times a second. A batch job also builds a nightly table of every customer's latest order, across 500 000 customers. One engineer wants a single SQL function for both using row_number() OVER (PARTITION BY customer_id ORDER BY created_at DESC). What do you do?
- DOC PostgreSQL 17 Tutorial: Window Functions
The gentlest introduction to OVER, PARTITION BY and frames, with the employee-salary examples everyone learns from. Read all of it first; it is three screens.
- DOC PostgreSQL 17: Window Function Calls (syntax and frame rules)
The precise definition of ROWS, RANGE and GROUPS, the default frame, peers, and EXCLUDE. Read section 4.2.8 whenever a running total surprises you; skip the rest of the page.
- DOC PostgreSQL 17: WITH Queries (Common Table Expressions)
Recursive evaluation, SEARCH and CYCLE, the materialisation rules since Postgres 12, and data-modifying CTEs. Sections 7.8.2 and 7.8.3 are the ones you will come back to.
- POST Modern SQL: WITH and the three-valued logic articles Markus Winand
The course plan's key reading for this chapter: what the standard says about WITH and how each database implements it, with compatibility charts. The site's other articles on FILTER and OVER are worth the same twenty minutes.
- TALK Postgres Window Magic Bruce Momjian
Eighty-five slides from a Postgres core developer that walk through every window function and frame option on tiny tables you can paste into psql. Use it as a workbook after the lab.
- PAPER Efficient Processing of Window Functions in Analytical SQL Queries Viktor Leis, Kan Kundhikanjana, Alfons Kemper, Thomas Neumann, 2015
How an engine evaluates windows: the sort, the partitioning, and the segment tree that makes arbitrary frames fast. Optional at this level; read it if you want to know why some frames are cheap and others are not. Read: sections 1 to 4; skip the parallelisation details in section 5 (PVLDB 8(10)).
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.