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.

Published 2026-05-09·Updated 2026-05-09

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

  1. Use GROUPING SETS to choose exact subtotal levels.
  2. Use ROLLUP for hierarchical subtotals and a grand total.
  3. 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 editor