GROUPING SETS, ROLLUP, and CUBE extend GROUP BY to create multiple summary levels within a single query. They are indispensable for dashboards, OLAP-style analysis, and multi-level reporting.
SELECT
region,
product,
SUM(amount) AS total_sales
FROM sales
GROUP BY GROUPING SETS (
(region),
(product),
()
);
Generates custom combinations: totals by region, by product, and the overall grand total in one pass.
SELECT
region,
product,
SUM(amount) AS total_sales
FROM sales
GROUP BY ROLLUP (region, product);
Builds hierarchical subtotals from detailed rows → region totals → overall totals.
SELECT
region,
product,
SUM(amount) AS total_sales
FROM sales
GROUP BY CUBE (region, product);
Returns every combination of the specified dimensions—perfect for multi-dimensional analytics.
SELECT
region,
product,
SUM(amount) AS total_sales,
GROUPING(region) AS region_flag,
GROUPING(product) AS product_flag
FROM sales
GROUP BY CUBE (region, product);
GROUPING() returns 1 when the column is aggregated (the NULL comes from a subtotal row).| Feature | GROUPING SETS | ROLLUP | CUBE |
|---|---|---|---|
| Purpose | Custom combinations | Hierarchical subtotals | All combinations |
| Grand total | Optional | Always included | Always included |
| Performance | Lightest | Moderate | Heaviest |
| Typical use | Tailored reports | Drill-down summaries | OLAP cubes |