Comparison · Grouping and calculating

GROUPING SETS, ROLLUP and CUBE: subtotal rows in SQL

GROUPING SETS computes the groups you list; ROLLUP adds hierarchical subtotal rows; CUBE computes every combination of the dimensions.

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.

GROUPING SETS
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

FormWhat it calculatesTypical use
GROUPING SETSOnly the groups you listReport 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.

Labelling subtotal rows
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, ROLLUP and CUBE.
  • SQL Server: supports all three forms in GROUP BY.
  • MySQL 8.4: documents ROLLUP and GROUPING(); for arbitrary combinations its syntax does not cover, an explicit alternative is UNION ALL.
  • SQLite: does not offer these modifiers in its GROUP BY; you can express the levels you need with several aggregates combined with UNION ALL.
Portable alternative
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.