Learn SQL Lesson
CUBE for All Combinations
`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.
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.