Learn SQL
SQL GROUPING SETS, ROLLUP, and CUBE Explained for Subtotals and Grand Totals
GROUPING SETS, ROLLUP, and CUBE help you build subtotal reports without stitching together many UNION ALL queries.
On This Page
Subtotal reports need more than one grouping level
Standard GROUP BY gives you one grouping level. Real reports often need detail totals, subtotals, totals by another dimension, and a grand total. GROUPING SETS, ROLLUP, and CUBE make that possible in one query.
SQL for Files uses small revenue examples so you can see exactly which rows each advanced grouping feature creates.
GROUPING SETS lets you choose exact grouping levels
GROUPING SETS lists the exact group combinations you want. The empty grouping set means the grand total.
SELECT region, product, SUM(amount) AS total_amount
FROM revenue
GROUP BY GROUPING SETS ((region), (product), ());ROLLUP creates hierarchical totals
ROLLUP is shorthand for detail rows, progressively broader subtotals, and a grand total. It is ideal when your dimensions have a natural hierarchy.
SELECT region, product, SUM(amount) AS total_amount
FROM revenue
GROUP BY ROLLUP (region, product);CUBE creates every combination
CUBE produces every grouping combination for the listed columns. With two columns, that means detail rows, region totals, product totals, and the grand total.
NULL can mark subtotal rows
Columns not included in a grouping level appear as NULL, which can be ambiguous if your original data also has NULL values.
Practice the GROUPING SETS, ROLLUP, and CUBE chapter
- Use GROUPING SETS to choose exact subtotal levels.
- Use ROLLUP for hierarchical subtotals and a grand total.
- Use CUBE for every dimension combination.
Continue in the editor
Open SQL for Files to add your own CSV, JSON, or Parquet files and try these examples locally in your browser.
Open editorRelated Learn SQL lessons
Related guides
SQL DISTINCT, GROUP BY, and HAVING: From Unique Values to Grouped Reports
DISTINCT cleans up repeated values, GROUP BY creates summaries per category, and HAVING filters those summaries after aggregation.
SQL Aggregate Functions: COUNT, SUM, MIN, MAX, and AVG Explained
Aggregate functions turn many rows into useful summary values, which is the foundation of reporting, dashboards, and quick data checks.
Practical SQL Examples for CSV, JSON, and Parquet Files
A compact collection of SQL patterns you can adapt for local file analysis in SQL for Files.