Learn SQL Lesson
Multi-Dimension Aggregates with GROUPING SETS
Sometimes you need aggregates along several dimensions in one result. `GROUPING SETS` lets you specify exactly which groups to compute.
For example, totals by region, by product, and an overall grand total:
SELECT region, product, SUM(amount) AS total_amount
FROM revenue
GROUP BY GROUPING SETS ((region), (product), ())
Each grouping set is a parenthesised list of columns. The empty set `()` means "aggregate everything with no grouping" — the grand total row.
Columns not part of a particular grouping set appear as `NULL` in the result. So the `(region)` set shows `NULL` in the product column, and the `()` set shows `NULL` in both.
That can be ambiguous if your original data also contains real `NULL` values. DuckDB supports `GROUPING(column)` when you need to tell whether a `NULL` came from a subtotal row or from the data itself.
Without `GROUPING SETS` you would need a separate query and `UNION ALL` for each combination. `GROUPING SETS` produces the same output in a single scan of the table.
Practice challenge
Use GROUPING SETS to compute SUM(amount) grouped by (region), (product), and the grand total (). Return region, product, and total_amount, ordered by region NULLS LAST, product NULLS LAST.