ROLLUP, CUBE & GROUPING SETS in SQL
Subtotals and grand totals in one scan
ROLLUP gives hierarchical totals (per-department rows plus a grand-total row); CUBE gives all column combinations; GROUPING SETS lists exact groupings wanted. NULLs in super-aggregate rows are ambiguous with real NULLs — identify them with GROUPING(). One pass with subtotals beats UNIONing multiple GROUP BYs.
ROLLUP hierarchies
GROUP BY ROLLUP (dept) yields per-dept rows plus a grand-total row (NULL key).
CUBE all combos
Every column combination — powerful, expensive on wide keys.
GROUPING SETS exact
List precisely which groupings to emit — no more, no less.
GROUPING() disambiguates
1 means total-NULL, 0 means real-NULL. Labels depend on it.
1SELECT department, COUNT(*) AS n FROM employees GROUP BY ROLLUP (department);
| department | n |
|---|---|
| Engineering | 3 |
| Marketing | 1 |
| Sales | 2 |
| null | 6 |
Three per-department rows plus a fourth where department is NULL — the grand total of 6. GROUPING() tells the report renderer to label that row Total instead of blank.
Dept rollup + total
Three groups plus grand total in one scan.
1SELECT department, COUNT(*) AS n FROM employees GROUP BY ROLLUP (department);
| department | n |
|---|---|
| Engineering | 3 |
| Marketing | 1 |
| Sales | 2 |
| null | 6 |
Exact sets
Only the groupings you list.
1SELECT department, COUNT(*) FROM employees GROUP BY GROUPING SETS ((department), ());
| department | count |
|---|---|
| Engineering | 3 |
| Sales | 2 |
| Marketing | 1 |
| null | 6 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.