Part 08 / Topic 10 of 10
Subtotals: GROUPING SETS, ROLLUP, CUBE
One GROUP BY, several groupings at once. ROLLUP adds the hierarchy of subtotals — per status and the grand total, in one pass:
SELECT COALESCE(status, 'ALL') AS status, count(*) AS orders
FROM orders
GROUP BY ROLLUP (status)
ORDER BY status = 'ALL', orders DESC;
status | orders
-----------+--------
delivered | 6
cancelled | 1
pending | 1
shipped | 1
ALL | 9
(5 rows)
The subtotal row arrives with NULL in the rolled-up column (COALESCE relabels it). With two columns, ROLLUP (a, b) yields (a,b) → (a) → (): detail, per-a subtotals, grand total. CUBE adds every combination; GROUPING SETS ((a), (b)) names exactly the sets you want:
SELECT date_trunc('month', order_date)::date AS month, status, count(*) AS orders
FROM orders
GROUP BY GROUPING SETS ((date_trunc('month', order_date)), (status))
ORDER BY month NULLS LAST, orders DESC, status;
month | status | orders
------------+-----------+--------
2025-01-01 | | 2
2025-02-01 | | 2
2025-03-01 | | 3
2025-04-01 | | 2
| delivered | 6
| cancelled | 1
| pending | 1
| shipped | 1
(8 rows)
One caution carried from Part 3: a real NULL in the data and a subtotal NULL look identical. The GROUPING() function tells them apart (1 = this NULL means subtotal) — reach for it the moment a rolled-up column is nullable.
🧪 Quick quiz — answer from memory, then check.
- What does
GROUP BY ROLLUP (status)add beyond plain GROUP BY? - How do you distinguish a subtotal NULL from a data NULL?
Show the answers
- The subtotal rows — for one column, a single grand-total row with status NULL.
GROUPING(col)— returns 1 for subtotal rows, 0 for real data.
Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.