Chapter 10 · Lesson 2 of 3

ROLLUP for Hierarchical Totals

Use ROLLUP to produce hierarchical subtotals and a grand total in one SQL query, such as revenue by region and then by product.

ROLLUP is a shorthand that creates progressively less detailed grouping sets, perfect for subtotals and a grand total.

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

ROLLUP(region, product) expands to three grouping sets:

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

In general, ROLLUP with n columns produces n+1 grouping sets, peeling one column off the right at each level. This mirrors how you build hierarchical reports: detail rows, then group subtotals, then a grand total.

The display order is not guaranteed by ROLLUP itself. Use ORDER BY to put subtotal and grand total rows where you want them.

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 ROLLUP(region, product) to compute SUM(amount) with detail rows, region subtotals, and a grand total. Return region, product, and total_amount, ordered by region NULLS LAST, product NULLS LAST.

Hint: GROUP BY ROLLUP (region, product) — this gives (region, product), (region), and () 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