Before continuing: This entry is part of the GROUP BY guide. If you are new to the topic, start with GROUP BY.
Examples
GROUPING SETS lets you compute several grouping levels in a single query. ROLLUP produces hierarchical levels and CUBE produces every combination of the dimensions given.
SELECT region, channel, SUM(amount) AS sales
FROM sales
GROUP BY GROUPING SETS (
(region, channel),
(region),
()
);The empty set () stands for the grand total.
Differences and trade-offs
Three tools, three purposes
| Form | What it calculates | Typical use |
|---|---|---|
GROUPING SETS | Only the groups you list | Report with specific levels |
ROLLUP(a,b) | (a,b), (a), () | Hierarchies with subtotal rows |
CUBE(a,b) | (a,b), (a), (b), () | Multidimensional analysis |
Why GROUPING() matters when NULL is present
Engines use NULL for the columns that do not take part in a subtotal row. But a data column can also contain a genuine NULL real. GROUPING(column_name) lets you tell the two situations apart on engines that support it.
SELECT
CASE WHEN GROUPING(region) = 1 THEN 'TOTAL' ELSE region END AS region,
SUM(amount) AS sales
FROM sales
GROUP BY ROLLUP (region);Do not just use COALESCE(region, 'TOTAL') if a real NULL value in region has its own meaning: you would be mixing missing data with a summary row.
Key differences between engines
- PostgreSQL: supports
GROUPING SETS,ROLLUPandCUBE. - SQL Server: supports all three forms in
GROUP BY. - MySQL 8.4: documents
ROLLUPandGROUPING(); for arbitrary combinations its syntax does not cover, an explicit alternative isUNION ALL. - SQLite: does not offer these modifiers in its
GROUP BY; you can express the levels you need with several aggregates combined withUNION ALL.
SELECT region, channel, SUM(amount) AS sales
FROM sales
GROUP BY region, channel
UNION ALL
SELECT region, NULL, SUM(amount)
FROM sales
GROUP BY region
UNION ALL
SELECT NULL, NULL, SUM(amount)
FROM sales;This alternative is longer, but it makes the levels explicit and lets you check the result on engines without GROUPING SETS.