What you'll learn: By the end of this lesson you will be able to choose between
GROUP BYand a window function by asking whether rows must collapse, say whatWHERE,HAVINGandFILTEReach remove and when, handleNULLin aggregates, tellrow_number,rankanddense_rankapart on ties, explain window frames, write top-N per group, and use chained and recursive CTEs knowing how PostgreSQL plans them. A lab on real PostgreSQL code prints every result.
Think of a school register. The head teacher wants "marks per class", so she folds every class into one line: one row out for many rows in. A form tutor wants "each pupil's mark next to the class average", so every pupil keeps their own line and the class figure is written beside it. Both are sums over groups of rows. They differ in one thing: whether the rows survive.
That difference is the whole lesson. GROUP BY collapses rows. A window function does not. A common table expression (CTE, the WITH clause) is a name you give to an intermediate result so a long report reads top to bottom. SQL joins and EXPLAIN ANALYZE plans are separate lessons in this module; for tables and rows, see Databases: the basics.
Verified with the PostgreSQL 18 documentation and the lab below on PGlite 0.6.1 (real PostgreSQL compiled to WebAssembly, which reports PostgreSQL 19.0), on 2026-12-01.
The core idea
An aggregate turns many rows into one value. Used with GROUP BY it returns one row per group. Used as a window function (with an OVER clause) it returns the same kind of value but keeps every input row. A CTE names a step so the next step can read it. Choose the shape you want back, then choose the tool.
Three illustrations run through the lesson: a minimal example (a 14-row orders table in three stores, small enough to check by hand), a realistic example (ShopStream's store-owner dashboard) and a failure example (a top-3 query that returns four rows because two orders tie). All data is illustrative. The table has id, store_id, shopper_id, placed_on, total_cents, a nullable discount_cents and status.
Aggregation: collapse rows into groups
GROUP BY store_id puts rows with the same store_id in one group, and each aggregate (count, sum, avg, min, max) computes one value per group. Two clauses filter, at different moments: WHERE selects input rows before groups and aggregates are computed, whereas HAVING selects group rows after. That is why WHERE must not contain an aggregate and HAVING normally does.
Figure 1. The order in which the clauses take effect. How to read this: left to right is the order of meaning, not the order you type the clauses. A window function sees only what survived WHERE, GROUP BY and HAVING, which is why it cannot be used inside them.
FILTER and NULL
An aggregate can take FILTER (WHERE ...), which removes rows only from that aggregate's input, so one pass can produce "all orders", "cancelled orders" and "delivered revenue" side by side where WHERE would change every column.
count(*) counts input rows; count(expression) counts rows where the value is not null; sum and avg use the non-null values. Except for count, aggregates return null when no rows are selected, so sum of no rows is null, not zero; coalesce supplies zero.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
4. NULL in aggregates: sum over no non-null input is NULL
select count(*) as rows_counted,
count(discount_cents) as non_null_discounts,
sum(discount_cents) as total_discount,
(select sum(discount_cents) from orders where false) as sum_of_nothing,
coalesce((select sum(discount_cents) from orders where false), 0) as with_coalesce
from orders
rows_counted | non_null_discounts | total_discount | sum_of_nothing | with_coalesce
-------------+--------------------+----------------+----------------+--------------
14 | 4 | 1100 | NULL | 0
Four of the 14 orders carry a discount, so count(discount_cents) is 4 while count(*) is 14, and a sum over nothing is NULL until coalesce.
Window functions: keep the rows, add the context
A window function calculates across a set of rows related to the current row, but does not group them into one output row: the rows keep their identities. The call needs an OVER clause. Inside it, PARTITION BY divides the rows into groups that share the same values, and ORDER BY sets the order in which the function processes rows in each partition. Any ordinary aggregate becomes a window function when an OVER clause follows it.
Figure 2. The same store_id partition, two outcomes. How to read this: the top path folds the 14 rows into one per store; the bottom path returns all 14 rows and attaches the store's figure to each. Use the top path for a summary table and the bottom path when each row needs its group's context.
Ranking: row_number, rank and dense_rank
row_number numbers the rows of a partition from 1. rank gives the row_number of the first row of its peer group, so it leaves gaps after ties. dense_rank counts peer groups, so it has no gaps. Peers are rows that are not distinct when you look only at the window's ORDER BY columns, and the ranking functions give the same answer to all peers. Two orders of 2,500 cents in store 2 are peers.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
6. Ranking with ties: row_number, rank and dense_rank
select store_id, id, total_cents,
row_number() over (partition by store_id order by total_cents desc, id) as row_number,
rank() over (partition by store_id order by total_cents desc) as rank,
dense_rank() over (partition by store_id order by total_cents desc) as dense_rank
from orders
where store_id in (1, 2)
order by store_id, row_number
store_id | id | total_cents | row_number | rank | dense_rank
---------+----+-------------+------------+------+-----------
1 | 3 | 3200 | 1 | 1 | 1
1 | 13 | 2600 | 2 | 2 | 2
1 | 1 | 2400 | 3 | 3 | 3
1 | 2 | 1800 | 4 | 4 | 4
1 | 4 | 1800 | 5 | 4 | 4
2 | 5 | 5000 | 1 | 1 | 1
2 | 8 | 4100 | 2 | 2 | 2
2 | 6 | 2500 | 3 | 3 | 3
2 | 7 | 2500 | 4 | 3 | 3
2 | 14 | 1200 | 5 | 5 | 4
In store 2 the tied 2,500 orders both get rank 3; the next order gets rank 5 with rank and 4 with dense_rank. row_number keeps the rows apart only because its window also orders by id: the ORDER BY alone does not say which peer comes first, so numbering needs a tie-breaker.
Frames: what "so far" means
The frame is the slice of the partition the function looks at for the current row. When a window has an ORDER BY and no frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: from the start of the partition through the current row, plus any following rows that are peers of it. In RANGE mode CURRENT ROW stretches to the last peer; in ROWS mode it means only the current row.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
7. Running total, default frame (RANGE) versus ROWS: ties are peers
select placed_on, total_cents,
sum(total_cents) over (order by placed_on) as running_default,
sum(total_cents) over (order by placed_on rows between unbounded preceding and current row) as running_rows
from orders
where store_id = 2
order by placed_on, running_rows
placed_on | total_cents | running_default | running_rows
-----------+-------------+-----------------+-------------
2026-03-01 | 5000 | 5000 | 5000
2026-03-02 | 2500 | 10000 | 7500
2026-03-02 | 2500 | 10000 | 10000
2026-03-04 | 4100 | 14100 | 14100
2026-03-05 | 1200 | 15300 | 15300
The two orders on 2026-03-02 are peers. The default frame gives both 10,000; the ROWS frame gives 7,500 to one and 10,000 to the other, a true row-by-row total. Which identical row gets which value is not defined, so order by a unique column when it matters.
A window over aggregates
Windows run after GROUP BY, so an aggregate can sit inside a window call: lag(sum(total_cents)) over (order by placed_on) is yesterday's revenue next to today's. lag returns the value from the row offset rows before (default 1), or NULL when there is none.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
8. A window over aggregates: daily revenue, previous day, change
select placed_on,
sum(total_cents) as day_cents,
lag(sum(total_cents)) over (order by placed_on) as prev_day_cents,
sum(total_cents) - lag(sum(total_cents)) over (order by placed_on) as change_cents
from orders
where store_id = 3
group by placed_on
order by placed_on
placed_on | day_cents | prev_day_cents | change_cents
-----------+-----------+----------------+-------------
2026-03-01 | 900 | NULL | NULL
2026-03-03 | 3700 | 900 | 2800
2026-03-04 | 3000 | 3700 | -700
The first day has no previous day, so both prev_day_cents and the change are NULL.
Top-N per group
Window functions are permitted only in the select list and in ORDER BY. To filter on one, compute it in an inner query (a sub-select or a CTE) and filter in the outer one:
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
9. Top 2 orders per store: a window in a CTE, then filter
with ranked as (
select store_id, id, total_cents,
row_number() over (partition by store_id order by total_cents desc, id) as rn
from orders
)
select store_id, id, total_cents
from ranked
where rn <= 2
order by store_id, rn
store_id | id | total_cents
---------+----+------------
1 | 3 | 3200
1 | 13 | 2600
2 | 5 | 5000
2 | 8 | 4100
3 | 12 | 3000
3 | 11 | 2200
The lab also sends a window function straight into WHERE, and PostgreSQL refuses it:
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
12. A window function is not allowed in WHERE
select id from orders where row_number() over (order by id) <= 2
ERROR: window functions are not allowed in WHERE
CTEs: name a step, read the query top to bottom
WITH defines auxiliary statements, called CTEs, that you can think of as temporary tables that exist for one query. Several can be chained, each reading the ones before it. The step names make a report self-documenting; what they cost depends on how PostgreSQL plans them.
How a CTE is planned
A non-recursive, side-effect-free CTE can be folded into the parent query so both are optimized together. By default that happens when the parent references it once and not when it references it more than once. MATERIALIZED forces separate calculation; NOT MATERIALIZED forces folding. The documentation names the price of the second case: the optimizer cannot push restrictions from the parent down into a multiply-referenced WITH query, since that might affect all uses of its output.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
13. CTE plans: EXPLAIN (COSTS OFF)
A. CTE used once: PostgreSQL inlines it
with c as (select * from orders where store_id = 1) select id from c where total_cents > 2000
Seq Scan on orders
Filter: ((total_cents > 2000) AND (store_id = 1))
B. The same CTE with AS MATERIALIZED
with c as materialized (select * from orders where store_id = 1) select id from c where total_cents > 2000
CTE Scan on c
Filter: (total_cents > 2000)
CTE c
-> Seq Scan on orders
Filter: (store_id = 1)
Plan A has no CTE node: both filters sit on one scan of orders. Plan B reads the CTE through a CTE Scan, with store_id evaluated inside the CTE.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
D. The CTE used twice, default
with c as (select * from orders where store_id = 1) select (select count(*) from c) as n, (select max(total_cents) from c) as top
Result
CTE c
-> Seq Scan on orders
Filter: (store_id = 1)
InitPlan expr_1
-> Aggregate
-> CTE Scan on c
InitPlan expr_2
-> Aggregate
-> CTE Scan on c c_1
Referenced twice, the default plan computes the CTE once (CTE c) and both references read it.
Recursive CTEs
A recursive CTE has a non-recursive term, then UNION or UNION ALL, then a recursive term that refers to the CTE's own output. PostgreSQL evaluates it in rounds: it runs the non-recursive term and puts the rows in a working table, then keeps evaluating the recursive term against the working table's current rows until a round yields no rows. With UNION (not UNION ALL) duplicate rows are discarded. Data that can loop, such as a graph with cycles, will loop forever unless the recursive part eventually returns nothing; the documentation suggests UNION to drop repeats, tracking visited values, or the CYCLE clause.
Figure 3. Evaluating a recursive CTE. How to read this: the loop is the recursive term; each round sees only the rows the previous round added, which is why a tree walk reaches children of children without a fixed depth.
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0 build, 2026-12-01):
11. Recursive CTE: walk the category tree
with recursive tree as (
select id, name, 0 as depth, name::text as path
from categories
where parent_id is null
union all
select c.id, c.name, t.depth + 1, t.path || ' > ' || c.name
from categories c
join tree t on c.parent_id = t.id
)
select depth, path
from tree
order by path
depth | path
------+------------------------------------
0 | Groceries
1 | Groceries > Bakery
2 | Groceries > Bakery > Bread
1 | Groceries > Dairy
2 | Groceries > Dairy > Cheese
2 | Groceries > Dairy > Milk
3 | Groceries > Dairy > Milk > Oat milk
The walk starts at the one category with no parent and adds a level per round.
Build it: every result, on real PostgreSQL code
This lab is the minimal example, a set of queries you can run and change.
Goal. See every result above on a table small enough to check by hand.
Setup. From the repository's examples/postgres-labs folder:
cd examples/postgres-labs && npm install
node --test labs/aggregation-windows-ctes/test.mjs
cd labs/aggregation-windows-ctes && node run.mjs
The first command runs 13 tests; the second prints the twelve queries, the rejected one and the plans (the file examples/postgres-labs/golden/aggregation-windows-ctes.txt). The queries are in labs/aggregation-windows-ctes/lab.mjs. The lab runs in PGlite, PostgreSQL compiled to WebAssembly, and returns dates as text so output does not depend on a time zone.
Break it. In step 2 change having sum(total_cents) > 8000 to > 12000: store 1 drops out and the HAVING test fails. Put it back and re-run.
Stretch. Add a moving average with rows between 1 preceding and 1 following, or ntile(4) per store.
What the lab leaves out. Data volume (14 rows show shape, not speed), indexes, GROUPING SETS and ROLLUP, and anything needing two connections. PGlite reports PostgreSQL 19.0 while this course targets 18, so the lesson states only what the 18 documentation also states.
Choosing the tool: the trade-offs
Figure 4. A decision path for a reporting query. How to read this: answer the first question by the shape of the result you need; the remaining questions only add structure around it.
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
GROUP BY and aggregates |
One row per group, simplest to read | Input rows are gone | Each row must stay with its group's figure |
| Window function | Rows stay, context attached, rankings and running totals | Cannot be filtered in WHERE; ties and frames need care |
You only need a summary table |
MATERIALIZED CTE |
Computed once, separate from the parent | The parent's filters are not pushed in | You rely on the parent's filter to narrow the CTE |
| Recursive CTE | Walks a tree or graph without a fixed depth | A cycle in the data can loop forever | The depth is fixed and small: a join is clearer |
In practice: ShopStream's store-owner dashboard
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. The figures are the lab's illustrative rows.
This is a realistic scenario, not a case history.
The situation
Store owners want a weekly page: revenue per day with the change from the day before, their three biggest orders, and a product-category tree. Today the dashboard service loads the week's orders and loops over them in code.
Starting architecture
Figure 5. The dashboard path after the change. How to read this: the service sends one query built from aggregates, windows and CTEs and receives summary rows, instead of pulling every order across the network and looping over them.
Options considered
| Option | Result | Risk |
|---|---|---|
| A. Loop in the service | Works for a prototype | Every order row crosses the network |
B. One SQL query with GROUP BY plus lag |
Daily revenue and change in one statement | Needs window knowledge on the team |
C. B plus row_number in a CTE for the top orders |
Top-N per store | Ties must be handled on purpose |
The decision
Option C. The daily figure is the lab's step 8 (grouped revenue, then lag); the top orders use step 9's shape (a window in a CTE, then rn <= 3); the category tree is step 11. Each query is written as named steps so a reviewer reads it top to bottom.
Rollout and verification
Before release the team compares the query's numbers with the old loop's on a sample of stores and keeps those fixtures as tests, as the lab does: totals, the change from the previous day, the first day's NULL and the rows returned per store.
The 2 a.m. failure
The page reads: one store's "top 3 orders" list shows four rows. Someone replaced row_number() with rank() to make ties fair. In the lab's store 2 two orders tie at 2,500 cents, so ranks run 1, 2, 3, 3 and a filter rank <= 3 returns four rows. PostgreSQL is right; the query asks a different question.
The check: run the inner query without the filter and read the rank column. The mitigation is to decide what a tie means: keep rank and accept four rows, or use row_number with a tie-breaker such as id so the list is always the same three. The lasting fix is a test fixture with a tie, which the lab provides.
Architect's notes
- Start from the shape of the answer. One row per group means
GROUP BY; every row plus context means a window. - Write the tie-breaker. A ranking window should end its
ORDER BYin a unique column. - Say which frame you mean. The default
RANGEframe treats ties as one step; ask forROWSfor row-by-row. - Check the plan before assuming a CTE is free or a fence. The default depends on how often it is referenced.
Common mistakes
- Putting an aggregate in
WHERE. UseHAVING, or compute it in a CTE. - Filtering a window function in
WHERE. Filter in an outer query. - Reading
sumof nothing as zero. It isNULL; usecoalesce. - Using
rankand expecting N rows. Ties return more than N. - Writing a recursive CTE over data that can loop. Use
UNION, track visited rows or useCYCLE.
Key takeaways
GROUP BYcollapses rows; a window function keeps them and adds group context.WHEREremoves rows before grouping,HAVINGremoves groups after,FILTERremoves rows from one aggregate only.count(column)counts non-null values, andsumof no rows isNULL.rankleaves gaps after ties,dense_rankdoes not, androw_numberneeds a tie-breaker.- With an
ORDER BYthe default frame runs from the partition start through the last peer of the current row. - A CTE used once is folded into its query by default;
MATERIALIZEDandNOT MATERIALIZEDoverride that.
Practice exercises
Exercise 1 (20 min). Write a query returning each store's cancelled share of orders with FILTER, and check it by hand.
Exercise 2 (45 min). Change step 6 to use ntile(2) per store, predict the output for five rows, then run it.
Exercise 3 (1 hour). Run "Break it". Then make the top-2 query use rank() instead of row_number() and say which stores return more than two rows.
Exercise 4 (2 hours). Design ShopStream's weekly store-owner page: each figure, its query shape, the tie rule, and a fixture for each failure in "Common mistakes".
Related reading
- Databases: the basics: tables, rows, indexes and transactions in one place.
- ShopStream Stage 3: Choosing the Right Data Store for Each Job: why orders and payments sit in a relational store.
- SQL joins and query plans with
EXPLAIN ANALYZEare separate lessons in this module.
Official documentation
- PostgreSQL 18, Aggregate Functions (tutorial) and Aggregate Functions (reference).
- PostgreSQL 18, Window Functions (tutorial) and Window Functions (reference).
- PostgreSQL 18, Value Expressions: aggregate expressions and window function calls.
- PostgreSQL 18, WITH Queries (Common Table Expressions).