GROUPING SETS, ROLLUP & CUBE for Multi-Level Subtotals
Compute multiple grouping levels and subtotals in one scan.
In plain words
One query gives you the detailed totals, the subtotals and the overall total at the same time.
Think of it like…
A sales report printed with a line for each product, a subtotal under each region, and a grand total at the bottom, all from one pass over the receipts.
Where you’ve seen it
SELECT region, product, SUM(revenue) FROM sales GROUP BY ROLLUP (region, product) ORDER BY region, product; returns each (region, product), a subtotal per region (product NULL) and a grand total (both NULL), ready for a report.
Words you’ll hear
- GROUPING SETS
- An explicit list of groupings to compute in one query.
- ROLLUP
- Hierarchical subtotals from left to right, plus a grand total.
- CUBE
- Subtotals for every combination of the listed columns (2ⁿ groupings).
- GROUPING(col)
- Returns 1 when col is aggregated away in that row, to tell subtotal NULLs from real NULLs.
Visual diagram
Theory & example queries
GROUPING SETS, ROLLUP and CUBE
GROUPING SETS is the general form: list each grouping you want, and the database computes them all, usually with a single scan, and stacks the results. () is the empty grouping, the grand total. Columns not part of a row's grouping come back as NULL.
ROLLUP(a, b, c) means (a, b, c), (a, b), (a), (): natural for hierarchies like year > month > day or country > state > city. CUBE(a, b, c) means all 2³ = 8 combinations, which suits cross-tab analysis but grows fast. You can mix them: GROUP BY year, ROLLUP (region, product).
SELECT region, product, SUM(revenue)FROM salesGROUP BY GROUPING SETS ((region), (product), ());PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative grouping-set totals4 sample rows
| region | product | sum |
|---|---|---|
| North | NULL | 1200 |
| NULL | Widget A | 700 |
| NULL | Widget B | 500 |
| NULL | NULL | 1200 |
Note: Sample rows show one region subtotal, two product subtotals and the grand total; NULL marks a rolled-up dimension and additional groups may exist.
gives totals per region, totals per product, and the grand total, without the detail rows.
Key takeaway: GROUPING SETS lists groupings; ROLLUP = hierarchy; CUBE = every combination.
Telling subtotal NULLs from real NULLs
If region itself can be NULL in the data, a NULL region in the result could be either a real "unknown region" group or a subtotal row. GROUPING(region) returns 1 for rows where region was rolled up and 0 otherwise, so you can label them reliably.
Support varies: PostgreSQL (9.5+), SQL Server, Oracle, Snowflake and BigQuery support all three. MySQL supports only GROUP BY a, b WITH ROLLUP and, since 8.0, the GROUPING() function. Sorting needs care too: ORDER BY GROUPING(region), region places subtotals after their detail rows.
SELECT CASE WHEN GROUPING(region) = 1 THEN 'All regions' ELSE region END AS region, CASE WHEN GROUPING(product) = 1 THEN 'All products' ELSE product END AS product, SUM(revenue)FROM salesGROUP BY ROLLUP (region, product);PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative labelled rollup4 sample rows
| region | product | sum |
|---|---|---|
| North | Widget A | 700 |
| North | Widget B | 500 |
| North | All products | 1200 |
| All regions | All products | 1200 |
Note: Illustrative North-only sales data. ROLLUP also returns detail and subtotal rows for every other region present.
Key takeaway: Use GROUPING() for labels; check your database's support.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
List the levels the report needs
Write down each total the report shows: per product within region, per region, overall.
detail · region subtotal · grand total
When to use it & trade-offs
What it is
GROUPING SETS computes several GROUP BYs in one query: GROUP BY GROUPING SETS ((region, product), (region), ()) returns per-product rows, per-region subtotals and a grand total. ROLLUP(a, b) is shorthand for the hierarchy (a, b), (a), (). CUBE(a, b) gives every combination: (a, b), (a), (b), (). Subtotal rows show NULL in the columns that were rolled up.
Why it matters: Finance and sales reports need detail lines, subtotals and a grand total together. Writing several queries and UNIONing them means several scans and messy code; ROLLUP does it in one. It's an advanced SQL interview topic, often paired with the GROUPING() function question.
When to reach for it
- Financial and sales reports with subtotals
- Feeding pivot-style dashboards with all totals at once
- Replacing UNION ALL of several GROUP BY queries
When to avoid or be careful
- CUBE over many columns (the number of groupings doubles with each one)
- Reading NULL as a subtotal when the data itself contains NULLs
- Expecting GROUPING SETS or CUBE in MySQL
ROLLUP vs CUBE vs UNION ALL of GROUP BYs
Strengths: Short, one scan, natural report shape.
Watch out: Order of columns defines the hierarchy.
Strengths: Every needed combination in one query.
Watch out: CUBE grows exponentially; not available in MySQL.
Strengths: Works everywhere and is easy to follow.
Watch out: Scans the data once per level; repetitive code.
Interview signals & numbers to know
When this topic comes up
- “Show subtotals and a grand total”
- “Totals by region, by product and overall”
- “What does ROLLUP do?”
- GROUPING() function
- Financial reporting
Benchmarks & rules of thumb
- n + 1
- groupings produced by ROLLUP of n columns
- 2ⁿ
- groupings produced by CUBE of n columns
- 1
- scan of the table, typically
Common mistakes & follow-ups
Common interview mistakes
- Treating every NULL in the result as a subtotal when the column has real NULLs.
- Using CUBE when only hierarchical subtotals were needed, producing confusing extra rows.
- Writing three GROUP BY queries with UNION ALL when one ROLLUP would do.
Likely interviewer follow-ups
- What's the difference between ROLLUP and CUBE?
- How do you tell a subtotal row from a row with a real NULL value?
- How many groupings does ROLLUP(year, month, day) produce?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply GROUPING SETS, ROLLUP & CUBE for Multi-Level Subtotals with hands-on SQL practice and interview Q&A.