Learn SQL Lesson

ROLLUP for Hierarchical Totals

`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.

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.

Open interactive editor