Lesson 9 of 13 · 13m
GROUP BY Beyond COUNT(*)
GROUPING SETS, FILTER, and WITHIN GROUP aggregates compute pivots, subtotals, and exact percentiles in one scan instead of N queries.
The dashboard wants per-region revenue, per-day revenue, and a grand total. The query most teams ship is three queries — or one query run twice with different GROUP BY and the results stitched in application code. Postgres can do it in one pass: GROUP BY GROUPING SETS ((region), (created_at::date), ()) produces all three aggregations from a single scan of the table, with NULL marking the rows that come from each set.
The wrong model: one GROUP BY per report
The model "one report, one query" feels obvious until you cost it. Three queries means three scans of the same heap, three aggregation passes, three rounds through the planner — and on a reporting table of 200 million rows, that's 3x the I/O for output the engine can emit in one pass. ROLLUP (a, b) is the common shorthand: it expands to grouping sets ((a,b), (a), ()) — the drill-down plus every subtotal. CUBE (a, b) expands to all four combinations ((a,b), (a), (b), ()) for cross-tabs.
The NULL ambiguity is real and needs handling: a NULL in the output might mean "the subtotal row" or might mean "the column was NULL in the data." GROUPING(region) returns 1 when that column isn't in the current grouping set — the disambiguator you use to label the row 'ALL' instead of NULL in the report layer.
FILTER: the pivot you'll actually write weekly
count(*) FILTER (WHERE status = 'failed') computes a conditional aggregate in the same pass as the unconditional one. The pre-FILTER idiom sum(CASE WHEN status='failed' THEN 1 ELSE 0 END) works identically — FILTER is just the readable version the SQL standard added — but the pattern is what matters: pivoted counts in one row.
SELECT created_at::date AS day,
count(*) AS total,
count(*) FILTER (WHERE status = 'failed') AS failed,
count(*) FILTER (WHERE amount > 1000) AS large
FROM orders GROUP BY 1 ORDER BY 1;One scan, four aggregates. The BI-tool-shaped alternative — a query per measure — is the N-scans problem again.
Ordered-set aggregates: percentiles done right
percentile_cont(0.95) WITHIN GROUP (ORDER BY duration_ms) is the answer to "what's our p95 latency" and it's an ordered-set aggregate: it sorts the group's values, then interpolates between neighbors at the 95th percentile position. It is not the average of the top values, not the 95th row, and not avg() of anything — percentile_cont interpolates (percentile_disc returns an actual observed value instead).
Every "p95" you see computed as avg(top 5%) or a LIMIT into a sorted list is approximating what WITHIN GROUP does exactly. The honest cost: it sorts each group, so at warehouse scale on billions of rows you reach for approximations like the tdigest extension — but on the scale most services run at, percentile_cont is the right tool and approx_percentile shortcuts are premature.
Where people reach for GROUP BY and shouldn't
mode() WITHIN GROUP (ORDER BY x) answers "the most common value." array_agg(x ORDER BY ts) builds an ordered array — the "concatenate event history per user" trick that powers audit logs in a single pass. And string_agg(x, ',') replaces the group-concat hacks other databases need GROUP_CONCAT for — with an ORDER BY inside so the concatenation is deterministic instead of scan-order luck.
The misuse pattern worth naming: GROUP BY used to deduplicate — SELECT DISTINCT or GROUP BY id to collapse "duplicate" rows. If you're grouping to remove duplicates rather than to aggregate, you're masking a data problem upstream. Fix the pipeline or use ROW_NUMBER dedup; don't let the aggregate hide it.
What to actually do
- Subtotals and drill-downs in one pass:
GROUPING SETS/ROLLUP/CUBE, label rows withGROUPING(). - Conditional counts and pivots:
FILTER (WHERE ...)— never "one query per measure." - p95/p99:
percentile_cont(0.95) WITHIN GROUP (ORDER BY x);percentile_discwhen the answer must be a row that exists. - "Most common value" and ordered concatenation:
mode(),array_agg,string_agg— all ordered-set tools. - If you're grouping just to dedupe, stop — that's a pipeline bug the query is papering over.
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.