Sub topic 12
Subtotals with ROLLUP, CUBE and GROUPING SETS
This chapter assumes you can write a GROUP BY query with several columns, use HAVING, and read a CASE expression. It also assumes you know that NULL means a missing value. All examples use the orders table from the earlier chapters and run on PostgreSQL. The differences in other databases come near the end.
The problem: one query, several levels of totals
A plain GROUP BY customer_id, status returns one row per combination. A report usually also needs a total per customer and a grand total. You could write three queries and combine them with UNION ALL. That scans the table three times and is easy to get out of sync.
ROLLUP, CUBE and GROUPING SETS are extensions of GROUP BY that compute several groupings in one pass. Each grouping is called a grouping set: a list of columns that defines one way of forming groups. The empty set () means "no columns", so the whole table is one group, which gives the grand total.
Sample data
Use this small table so the results are easy to check by hand.
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL,
amount NUMERIC(10,2) NOT NULL
);
INSERT INTO orders (order_id, customer_id, status, amount) VALUES
(1, 10, 'paid', 100.00),
(2, 10, 'refunded', 40.00),
(3, 20, 'paid', 200.00),
(4, 20, 'paid', 50.00);The grand total of amount is 390.00.
ROLLUP: hierarchical subtotals
ROLLUP (a, b) produces the grouping sets (a, b), (a) and (). It drops columns from the right, one at a time. Use it when the columns form a hierarchy, such as year, month and day, or country, region and city.
SELECT customer_id,
status,
SUM(amount) AS total_amount
FROM orders
GROUP BY ROLLUP (customer_id, status)
ORDER BY customer_id, status;| customer_id | status | total_amount |
|---|---|---|
| 10 | paid | 100.00 |
| 10 | refunded | 40.00 |
| 10 | NULL | 140.00 |
| 20 | paid | 250.00 |
| 20 | NULL | 250.00 |
| NULL | NULL | 390.00 |
The NULL in status on the third row means "all statuses for customer 10". The last row, with NULL in both columns, is the grand total. PostgreSQL sorts NULL last in ascending order, which puts each subtotal after its detail rows. Other databases may place NULL first, so do not rely on the default.
Column order matters. ROLLUP (status, customer_id) gives subtotals per status, not per customer.
With n columns, ROLLUP produces n + 1 grouping sets.
CUBE: every combination
CUBE (a, b) produces (a, b), (a), (b) and (). It builds subtotals for every subset of the columns. Use it for cross-tabulated reports where no column is "above" another.
SELECT customer_id,
status,
SUM(amount) AS total_amount
FROM orders
GROUP BY CUBE (customer_id, status)
ORDER BY customer_id, status;Compared with the ROLLUP result, you get two extra rows: NULL, paid, 350.00 and NULL, refunded, 40.00. These are totals per status across all customers.
With n columns, CUBE produces 2^n grouping sets. Five columns give 32 grouping sets, which can be expensive and produces many rows you may not need. If you only want some of them, name them explicitly.
GROUPING SETS: choose exactly which groupings
GROUPING SETS takes a list of the groupings you want. ROLLUP and CUBE are shorthand for specific lists.
SELECT customer_id,
status,
SUM(amount) AS total_amount
FROM orders
GROUP BY GROUPING SETS ((customer_id), (status), ())
ORDER BY customer_id, status;This returns a total per customer, a total per status and the grand total. It does not return the per-customer-per-status detail rows, because (customer_id, status) is not in the list.
You can mix plain columns with these extensions. GROUP BY customer_id, ROLLUP (status) always groups by customer_id and rolls up only status. The result has per-status rows and a per-customer subtotal, but no grand total.
The diagram shows that ROLLUP is the shortest list, CUBE is the full list, and GROUPING SETS lets you write any list.
Telling subtotal NULLs from data NULLs
The NULL that marks a subtotal looks the same as a real NULL stored in the column. Suppose some orders had status set to NULL. The row 10, NULL, 140.00 could then be either a subtotal or the total of customer 10's orders with a missing status.
The GROUPING function resolves this. GROUPING(column) returns 1 if the column was rolled up in that output row, and 0 if it is a real group value. A real NULL in the data still gives 0.
SELECT CASE WHEN GROUPING(customer_id) = 1
THEN 'ALL CUSTOMERS'
ELSE CAST(customer_id AS VARCHAR(20)) END AS customer,
CASE WHEN GROUPING(status) = 1
THEN 'ALL STATUSES'
ELSE status END AS status,
SUM(amount) AS total_amount
FROM orders
GROUP BY ROLLUP (customer_id, status)
ORDER BY GROUPING(customer_id), customer_id,
GROUPING(status), status;Two details matter here:
- Both branches of a
CASEmust have compatible types. That is whycustomer_idis cast to text before it is mixed with a label. - Ordering by
GROUPING(...)first gives a stable layout: detail rows, then subtotals, then the grand total at the bottom. This does not depend on how the database sortsNULL.
COALESCE(status, 'ALL') is tempting but wrong. It would also relabel real NULL values as "ALL".
When you list several columns, GROUPING(a, b) returns a bitmask in some databases (PostgreSQL, SQL Server, Oracle). Each argument contributes one bit, with the first argument as the highest bit. For example, GROUPING(customer_id, status) is 3 on the grand total row, 1 on a per-customer subtotal and 0 on a detail row.
Filtering with HAVING and WHERE
The evaluation order from the earlier chapter still applies. WHERE removes rows before any grouping set is formed, so it affects every level of subtotal. HAVING filters the output rows after all grouping sets are computed, and it can remove detail rows, subtotal rows or both.
SELECT customer_id,
status,
SUM(amount) AS total_amount
FROM orders
WHERE status = 'paid'
GROUP BY ROLLUP (customer_id, status)
HAVING SUM(amount) > 100;Here only paid orders enter the groups, so the grand total becomes 350.00. The HAVING clause then drops any row, subtotal or not, whose sum is 100.00 or less. A subtotal can survive while some of its detail rows are removed, so the visible rows may no longer add up to the subtotal shown.
To keep only subtotal rows, filter on GROUPING in HAVING, for example HAVING GROUPING(status) = 1.
Database support
| Database | ROLLUP | CUBE | GROUPING SETS | GROUPING() |
|---|---|---|---|---|
| PostgreSQL | `ROLLUP (...)` | Yes | Yes | Yes |
| SQL Server | `ROLLUP (...)` | Yes | Yes | Yes |
| Oracle | `ROLLUP (...)` | Yes | Yes | Yes |
| MySQL 8 | `GROUP BY a, b WITH ROLLUP` | No | No | Yes |
| SQLite | No | No | No | No |
On MySQL, the equivalent of the first example is GROUP BY customer_id, status WITH ROLLUP. Replace CUBE and GROUPING SETS with UNION ALL of separate GROUP BY queries. SQLite needs the UNION ALL approach for every case.
The UNION ALL fallback for the GROUPING SETS ((customer_id), (status), ()) example looks like this:
SELECT customer_id, NULL AS status, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
UNION ALL
SELECT NULL, status, SUM(amount)
FROM orders
GROUP BY status
UNION ALL
SELECT NULL, NULL, SUM(amount)
FROM orders;On PostgreSQL, the first column of the first branch is an integer, and the bare NULL values in later branches take that type. If a column's type is ambiguous, add an explicit cast such as CAST(NULL AS VARCHAR(20)).
Common mistakes
- Reading a subtotal NULL as data. Use
GROUPING()whenever the grouped columns can themselves containNULL. - Using CUBE when ROLLUP is enough.
CUBEon many columns grows as2^nand returns rows nobody reads. - Wrong column order in ROLLUP. The subtotals follow the order you write, from right to left.
- Expecting HAVING to keep totals consistent. It filters each output row independently.
- Adding a sort on a column and expecting subtotals to follow detail rows. Sort by
GROUPING(...)explicitly. - Using SUM on an average. A subtotal of
AVG(amount)is the average of the rows in that group, not the average of the detail averages. Aggregates are recomputed from the underlying rows at each level, which is usually what you want.
Exercise
Using the sample orders table, write a query that returns the total amount per status and a grand total, but no per-customer rows. Label the grand total row 'ALL STATUSES'. What rows and amounts does it return?
Show answer
SELECT CASE WHEN GROUPING(status) = 1 THEN 'ALL STATUSES' ELSE status END AS status, SUM(amount) AS total_amount FROM orders GROUP BY ROLLUP (status) ORDER BY GROUPING(status), status; It returns paid 350.00, refunded 40.00 and ALL STATUSES 390.00. GROUP BY GROUPING SETS ((status), ()) gives the same result.
Exercise
How many grouping sets does CUBE (customerid, status, region) produce, and how many does ROLLUP (customerid, status, region) produce? Which one would you pick for a year, month, day report?
Show answer
CUBE produces 2^3 = 8 grouping sets. ROLLUP produces 3 + 1 = 4. For year, month and day, pick ROLLUP, because the columns form a hierarchy and subtotals per month alone, without a year, would not be meaningful.