Skip to content

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 with GROUPING().
  • Conditional counts and pivots: FILTER (WHERE ...) — never "one query per measure."
  • p95/p99: percentile_cont(0.95) WITHIN GROUP (ORDER BY x); percentile_disc when 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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.