skip to content

ROLLUP, CUBE and GROUPING SETS

subtotals and a grand total in one query, and GROUPING() to tell their NULLs from yours.

address
everything.analytics.grouping_sets
part
part 4, windows, grouping and recursion
chapter
chapter 2 of 11
reading time
7 min

GROUPING SETS runs several GROUP BYs in one query and stacks the results: detail rows, subtotals and a grand total together. ROLLUP (a, b) is shorthand for the sets (a, b), (a) and (): a hierarchy of subtotals. CUBE (a, b) is every combination.

in a subtotal row, the columns that were rolled up come out NULL. GROUPING() tells those NULLs apart from NULLs that were in your data.

the picture

you know the spreadsheet report with a subtotal under every year and a grand total at the bottom? the SQL version used to be three queries glued with UNION ALL: one GROUP BY year, status, one GROUP BY year, one with no GROUP BY at all. ROLLUP is those three, in one query, in one pass over the table.

think of counting votes. first by polling station and party (the detail), then you add up each station's sheet (a subtotal per station), then everything (the grand total). same ballots each time; you just stop distinguishing one more column at each level.

group by =
query.sql
  1. 1SELECT year, status, count(*) AS orders, GROUPING(year, status) AS g
  2. 2FROM (SELECT extract(year FROM ordered_at)::int AS year, status FROM orders) AS o
  3. 3GROUP BY year, status
  4. 4ORDER BY year NULLS LAST, status NULLS LAST;
the result for GROUP BY year, status
yearint4statustextordersint8gint4
2025cancelled1830
2025delivered48640
2025refunded470
2026cancelled1340
2026delivered44880
2026paid620
2026placed510
2026refunded510
2026shipped1200
(9 rows)

plain GROUP BY: one row per year and status that exists. 9 rows, and GROUPING() is 0 on every one: nothing is rolled up.

real output, postgres 18.6 (PGlite 0.5.12) · grouping-sets
switch the grouping. the plain GROUP BY gives 9 rows. ROLLUP adds a subtotal per year and a grand total; CUBE also adds a total per status; GROUPING SETS gives only the sets you list. g is GROUPING(year, status): 0 for a detail row, more for a subtotal.

look at ROLLUP's extra rows. 2025 | null | 5,094 is every order from 2025, whatever its status. null | null | 10,000 is every order. the NULL means "all of them" there, not "unknown". more on that collision below.

the three spellings

all three are ways to write a list of grouping sets, and postgres expands them before it runs anything:

  • n + 1 sets
  • ├── (year, status)the detail rows
  • ├── (year)a subtotal per year
  • └── ()the grand total
  • 2^n sets
  • ├── (year, status)the detail rows
  • ├── (year)a subtotal per year
  • ├── (status)a subtotal per status
  • └── ()the grand total
  • exactly what you list
  • ├── (year)
  • └── (status)
what ROLLUP and CUBE expand to. ROLLUP drops columns from the right, one at a time. CUBE takes every subset: 2ⁿ sets for n columns.

so this query and the UNION ALL of three GROUP BYs return the same rows (with NULL standing in for the columns a set doesn't group by):

sqldb=shop
SELECT year, status, count(*) AS orders
FROM (SELECT extract(year FROM ordered_at)::int AS year, status FROM orders) AS o
GROUP BY ROLLUP (year, status)
ORDER BY year NULLS LAST, status NULLS LAST;
output, from postgres 18.6
SELECT 12
yearint4statustextordersint8
2025cancelled183
2025delivered4864
2025refunded47
2025null5094
2026cancelled134
2026delivered4488
2026paid62
2026placed51
2026refunded51
2026shipped120
2026null4906
nullnull10000
(12 rows)

column order matters for ROLLUP, since it's a hierarchy: ROLLUP (status, year) gives a subtotal per status instead. CUBE doesn't care about order. and you can mix: GROUP BY year, ROLLUP (status, kind) keeps year in every set and rolls up the rest.

predict the output
sql
SELECT a, b, count(*)
FROM (VALUES (1, 'x'), (1, 'y'), (2, 'x')) AS t (a, b)
GROUP BY CUBE (a, b);
-- how many rows come back besides the 3 detail rows?
sqlempty db
SELECT a, b, count(*) AS n, GROUPING(a, b) AS g
FROM (VALUES (1, 'x'), (1, 'y'), (2, 'x')) AS t (a, b)
GROUP BY CUBE (a, b)
ORDER BY g, a, b;
output, from postgres 18.6
SELECT 8
aint4btextnint8gint4
1x10
1y10
2x10
1null21
2null11
nullx22
nully12
nullnull33
(8 rows)

GROUPING(): whose NULL is it?

the NULL in a subtotal row means "rolled up". but your data can hold NULLs of its own, and then the two look exactly alike. the shop has three products with no category:

show =
query.sql
  1. 1SELECT category, count(*) AS products
  2. 2FROM products
  3. 3GROUP BY ROLLUP (category)
  4. 4ORDER BY products, category;
the result for category
categorytextproductsint8
null3
books12
games14
garden15
pets17
kitchen19
audio21
outdoor22
toys24
office26
bath27
null200
(12 rows)

ROLLUP over category: two rows say NULL. one is the three products that have no category, the other is the grand total. nothing in the output says which is which.

real output, postgres 18.6 (PGlite 0.5.12) · grouping-sets
switch between the plain column and the labelled one. with just category, two rows say null: the three uncategorised products, and the grand total of 200. GROUPING(category) is 1 only on the rolled-up row, so it can label them.

GROUPING(col) is 0 when col is part of the current row's grouping set, 1 when it was rolled up. with several arguments it packs those bits into a number, the first argument as the highest bit. for GROUPING(year, status): 0 is a detail row, 1 is a per-year subtotal (status rolled up), 2 a per-status subtotal, 3 the grand total. that number is also the cleanest way to sort a report: details first, then subtotals, then the total, or the other way round.

sqldb=shop
SELECT CASE GROUPING(year, status)
         WHEN 0 THEN 'detail' WHEN 1 THEN 'year total'
         WHEN 2 THEN 'status total' ELSE 'grand total' END AS kind,
       year, status, count(*) AS orders
FROM (SELECT extract(year FROM ordered_at)::int AS year, status FROM orders) AS o
GROUP BY CUBE (year, status)
HAVING GROUPING(year, status) > 0
ORDER BY GROUPING(year, status), year, status;
output, from postgres 18.6
SELECT 9
kindtextyearint4statustextordersint8
year total2025null5094
year total2026null4906
status totalnullcancelled317
status totalnulldelivered9352
status totalnullpaid62
status totalnullplaced51
status totalnullrefunded98
status totalnullshipped120
grand totalnullnull10000
(9 rows)

HAVING works per grouping set, like it works per group: here it keeps only the subtotal rows.

one pass, not three

ROLLUP isn't a UNION ALL in disguise. postgres plans all the sets together, often in one sort or one hash pass:

sqldb=shop
EXPLAIN (COSTS OFF)
SELECT year, status, count(*)
FROM (SELECT extract(year FROM ordered_at)::int AS year, status FROM orders) AS o
GROUP BY ROLLUP (year, status);
output, from postgres 18.6
EXPLAIN
MixedAggregate Hash Key: (EXTRACT(year FROM orders.ordered_at))::integer, orders.status Hash Key: (EXTRACT(year FROM orders.ordered_at))::integer Group Key: () -> Seq Scan on orders

a MixedAggregate: one hash table per grouping set (Hash Key for (year, status), and for (year)), plus Group Key: (), the single group of the grand total. all three are filled from the same scan of orders. the three-query UNION ALL would read orders three times. (aggregation algorithms has hash vs sort aggregation.)

keylines

  • GROUPING SETS runs several GROUP BYs in one query and stacks the results.
  • ROLLUP (a, b) = (a, b), (a), (): a hierarchy of subtotals. order matters.
  • CUBE (a, b) = every subset of the columns: 2ⁿ grouping sets.
  • rolled-up columns come out NULL. GROUPING(col) = 1 tells them from your own NULLs.
  • it's one pass over the data, not a UNION ALL of separate scans.