Chapter 10 · Lesson 3 of 3

CUBE for All Combinations

Use CUBE to aggregate every combination of the listed columns, producing all subtotals for region and product in one result.

CUBE goes further than ROLLUP: it produces every possible combination of the listed columns.

SELECT region, product, SUM(amount) AS total_amount
FROM revenue
GROUP BY CUBE (region, product)

CUBE(region, product) expands to four grouping sets:

(region, product) — detail level (region) — per region (product) — per product () — grand total

With n columns, CUBE produces 2^n grouping sets. That makes it ideal for full cross-tabulation reports where you want totals along every dimension.

CUBE is equivalent to writing out a GROUPING SETS clause that lists every subset of the columns. The result is the same, but CUBE is more concise.

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 CUBE(region, product) to compute SUM(amount) for every combination of region and product. Return region, product, and total_amount, ordered by region NULLS LAST, product NULLS LAST.

Hint: GROUP BY CUBE (region, product) — this produces 2^2 = 4 grouping sets.

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in GROUPING SETS, ROLLUP, and CUBE

Produce subtotals and grand totals in a single query with GROUPING SETS, ROLLUP, and CUBE.

  1. 01 · Multi-Dimension Aggregates with GROUPING SETS
  2. 02 · ROLLUP for Hierarchical Totals
  3. 03 · CUBE for All Combinations

Related guides