Grouping sets, ROLLUP and CUBE
Overview
Reports often need totals at several levels at once: sales by country and city, with a subtotal for each country and a grand total at the bottom — the kind of thing a spreadsheet pivot table produces. You could run three queries and glue them together, but SQL can do it in one with grouping sets, and its two shortcuts, ROLLUP and CUBE.
The problem
You already know how to count customers per country and city:
SELECT country, city, count(*) AS customers
FROM customers
WHERE country IN ('India', 'USA')
GROUP BY country, city
ORDER BY country, city; country | city | customers
---------+---------+-----------
India | Mumbai | 1
India | Pune | 2
USA | Austin | 1
USA | Seattle | 1
(4 rows)But you’d also like a line per country (India: 3, USA: 2) and an overall total (5). That’s three different groupings of the same rows.
ROLLUP: subtotals and a grand total
ROLLUP (a, b) produces the groups for (a, b), then rolls up to (a), then to the grand total ():
SELECT country, city, count(*) AS customers
FROM customers
WHERE country IN ('India', 'USA')
GROUP BY ROLLUP (country, city)
ORDER BY country, city; country | city | customers
---------+---------+-----------
India | Mumbai | 1
India | Pune | 2
India | | 3
USA | Austin | 1
USA | Seattle | 1
USA | | 2
| | 5
(7 rows)The extra rows are the subtotals. In them, the column that was “rolled up” is NULL, meaning “all cities” (or, in the last row, “all countries and all cities”). With ORDER BY, the NULLs sort last within each country, so each subtotal sits right below its details — just like a report.
The order of columns in ROLLUP matters: it rolls up from right to left. ROLLUP (country, city) gives country subtotals; ROLLUP (city, country) would give per-city subtotals, which makes no sense here.
Labelling total rows with GROUPING()
The NULLs in total rows are ambiguous: is it a subtotal, or does the data genuinely contain a NULL? The GROUPING(column) function settles it: it returns 1 if the column was rolled up in that row and 0 otherwise. Use it to label totals and to sort them where you want:
SELECT CASE WHEN GROUPING(country) = 1 THEN 'All countries' ELSE country END AS country,
CASE WHEN GROUPING(country) = 1 THEN 'Grand total'
WHEN GROUPING(city) = 1 THEN 'Subtotal'
ELSE city END AS city,
count(*) AS customers
FROM customers
WHERE country IN ('India', 'USA')
GROUP BY ROLLUP (country, city)
ORDER BY GROUPING(country), country, GROUPING(city), city; country | city | customers
---------------+-------------+-----------
India | Mumbai | 1
India | Pune | 2
India | Subtotal | 3
USA | Austin | 1
USA | Seattle | 1
USA | Subtotal | 2
All countries | Grand total | 5
(7 rows)Ordering by GROUPING(...) first keeps every total row below the rows it summarises, regardless of how the labels would sort alphabetically.
When the grouped column can’t contain real NULLs, COALESCE(country, 'All countries') is a shorter way to label the total — but GROUPING() is always correct.
A rolled-up time report
ROLLUP is especially handy for periods. Orders per quarter and month, with quarterly subtotals and a year total:
SELECT extract(quarter FROM ordered_at) AS quarter,
extract(month FROM ordered_at) AS month,
count(*) AS orders,
sum(shipping_fee) AS shipping
FROM orders
WHERE status <> 'cancelled'
GROUP BY ROLLUP (extract(quarter FROM ordered_at), extract(month FROM ordered_at))
ORDER BY quarter, month; quarter | month | orders | shipping
---------+-------+--------+----------
1 | 1 | 3 | 11.49
1 | 2 | 2 | 15.25
1 | 3 | 3 | 11.49
1 | | 8 | 38.23
2 | 4 | 2 | 13.99
2 | 5 | 2 | 16.75
2 | 6 | 1 | 6.50
2 | | 5 | 37.24
3 | 7 | 1 | 7.25
3 | 8 | 1 | 0.00
3 | 9 | 2 | 13.99
3 | | 4 | 21.24
4 | 10 | 2 | 13.75
4 | 11 | 3 | 14.49
4 | | 5 | 28.24
| | 22 | 124.95
(16 rows)Each quarter’s last row (with an empty month) is its subtotal, and the final row is the year.
CUBE: every combination
CUBE (a, b) produces all combinations of the listed columns: (a, b), (a), (b) and (). It’s what you want for a cross-tab where both dimensions deserve totals — orders by status and quarter, with totals per status, per quarter, and overall:
SELECT status,
extract(quarter FROM ordered_at) AS quarter,
count(*) AS orders
FROM orders
WHERE ordered_at >= '2026-07-01'
GROUP BY CUBE (status, extract(quarter FROM ordered_at))
ORDER BY status, quarter; status | quarter | orders
-----------+---------+--------
delivered | 3 | 3
delivered | | 3
paid | 4 | 2
paid | | 2
pending | 4 | 2
pending | | 2
shipped | 3 | 1
shipped | 4 | 1
shipped | | 2
| 3 | 4
| 4 | 5
| | 9
(12 rows)Rows with an empty quarter are status totals; rows with an empty status are quarter totals (Q3: 4 orders, Q4: 5); the last row is everything since July. With n columns, CUBE produces 2ⁿ groupings, so use it on a few columns at a time.
GROUPING SETS: exactly what you ask for
ROLLUP and CUBE are shortcuts. The general form, GROUPING SETS, lists each grouping explicitly, with () meaning the grand total:
SELECT country, status, count(*) AS orders
FROM orders o
JOIN customers c ON c.id = o.customer_id
GROUP BY GROUPING SETS ((country), (status), ())
ORDER BY country, status; country | status | orders
-----------+-----------+--------
France | | 2
India | | 8
Nigeria | | 3
Singapore | | 3
Spain | | 2
UK | | 4
USA | | 2
| cancelled | 2
| delivered | 16
| paid | 2
| pending | 2
| shipped | 2
| | 24
(13 rows)(This query joins orders to customers to get each order’s country — joins are the next chapter.) The result stacks three independent summaries — orders per country, orders per status, and the total — in one query. ROLLUP (a, b) is exactly GROUPING SETS ((a, b), (a), ()), and CUBE (a, b) is GROUPING SETS ((a, b), (a), (b), ()).
When to use them
- Reports with subtotals — finance, sales and operations reports exported to spreadsheets or PDFs.
- Feeding BI tools that expect pre-computed totals.
- Saving round trips — one query instead of several, and the database reads the data only once.
When you only need a grand total in an application, it’s often simpler to compute it in code or run a second tiny query. Use grouping sets when the totals belong in the data.
Other databases:
ROLLUP,CUBE,GROUPING SETSandGROUPING()are standard SQL and work in PostgreSQL, SQL Server, Oracle, Snowflake and BigQuery. MySQL supports onlyGROUP BY a, b WITH ROLLUP; SQLite supports none of them.
Orders by status, with a total
Produce a small report of orders per status: status, orders (how many) and shipping (the sum of shipping fees), plus a grand-total row, using ROLLUP. Label the grand-total row's status 'TOTAL' by testing GROUPING(status), and sort so the statuses come alphabetically with the total row last.
SELECT status,
count(*) AS orders,
sum(shipping_fee) AS shipping
FROM orders
GROUP BY status
ORDER BY status;SELECT CASE WHEN GROUPING(status) = 1 THEN 'TOTAL' ELSE status END AS status,
count(*) AS orders,
sum(shipping_fee) AS shipping
FROM orders
GROUP BY ROLLUP (status)
ORDER BY GROUPING(status), status;Summary
- GROUP BY ROLLUP (a, b) returns the groups for (a, b), subtotals for each a, and a grand total — all in one query.
- CUBE (a, b) returns every combination of groupings: (a, b), (a), (b) and the grand total.
- GROUPING SETS ((a), (b), ()) lists exactly the groupings you want.
- In subtotal rows, the rolled-up columns are NULL; GROUPING(column) returns 1 for those rows, so you can label and sort them.
- These are standard SQL and are supported by PostgreSQL, SQL Server, Oracle and others (MySQL has WITH ROLLUP).