Chapter 10 · Lesson 1 of 3
Multi-Dimension Aggregates with GROUPING SETS
Compute several groupings in one query with GROUPING SETS, returning totals by region, by product, and a grand total together.
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.
Sample data
This lesson loads the revenue table (4 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for revenue
CREATE OR REPLACE TABLE revenue (
region VARCHAR,
product VARCHAR,
amount INTEGER
);
INSERT INTO revenue VALUES
('East', 'Widget', 100),
('East', 'Gadget', 200),
('West', 'Widget', 150),
('West', 'Gadget', 250);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.
Hint: GROUP BY GROUPING SETS ((region), (product), ()) — remember to alias SUM(amount) as total_amount.
Run your query in the editor and the lesson checks the result automatically.
Lessons in GROUPING SETS, ROLLUP, and CUBE
Produce subtotals and grand totals in a single query with GROUPING SETS, ROLLUP, and CUBE.