Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Learn how to use SQL GROUPING SETS, ROLLUP, and CUBE to calculate subtotals and grand totals in a single query across PostgreSQL, MySQL, and BigQuery.
Quick answer
GROUPING SETS, ROLLUP, and CUBE are advanced SQL GROUP BY extensions that calculate multiple levels of aggregation within a single query pass. They replace repetitive UNION ALL queries by producing subtotals, grand totals, and multi-dimensional cross-tabulations directly in the database engine.
FAQs
What is the main difference between ROLLUP and CUBE in SQL?
ROLLUP produces hierarchical subtotals by dropping columns from right to left, while CUBE produces all possible mathematical combinations of the specified columns.
How do I know if a NULL in the result set is a subtotal or actual NULL data?
Use the GROUPING(column) function. It returns 1 if the NULL represents an aggregated subtotal row, and 0 if it represents a literal NULL value from the underlying data.
Does SQLite support GROUPING SETS or ROLLUP?
SQLite does not support GROUPING SETS, ROLLUP, or CUBE. In SQLite, you must use UNION ALL queries or perform subtotal calculations in the application layer.
Can I combine standard GROUP BY columns with GROUPING SETS?
Yes. In SQL dialects like PostgreSQL and Oracle, you can specify composite groupings like GROUP BY department, ROLLUP(year, quarter).
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
Business dashboards and financial reports often require aggregated metrics across multiple dimensional hierarchies: sales by region and store, sales by region alone, and the grand total across all stores. Historically, developers accomplished this by stitching together three or four separate queries using UNION ALL.
Stitching queries with UNION ALL scans the underlying table repeatedly and clutters your SQL scripts. Standard SQL provides GROUPING SETS, ROLLUP, and CUBE to calculate all required subtotals and grand totals in a single query execution pass, reducing I/O and producing clean reporting datasets.
The problem with multiple UNION ALL queries
When you write multiple queries joined by UNION ALL to produce subtotals, the database must execute each branch independently. If your table contains 50 million rows, four queries mean 200 million rows scanned. Read our guide to SQL window functions vs GROUP BY for how different aggregation strategies compare.
The inefficient UNION ALL anti-pattern
-- Bad pattern: scans sales table 3 timesSELECT region, store, SUM(revenue) AS total_revenueFROM store_salesGROUP BY region, storeUNION ALLSELECT region, NULL AS store, SUM(revenue) AS total_revenueFROM store_salesGROUP BY regionUNION ALLSELECT NULL AS region, NULL AS store, SUM(revenue) AS total_revenueFROM store_sales;
In addition to scanning the table three times, maintaining this query is error-prone. Any modification to the WHERE filter must be copied identically into every branch.
GROUPING SETS: explicit dimensional combinations
The GROUPING SETS clause allows you to specify the exact combinations of columns you want to group by. The database engine calculates all specified groupings during a single scan of the dataset.
Using GROUPING SETS for targeted subtotals
SELECT region, store, SUM(revenue) AS total_revenueFROM store_salesGROUP BY GROUPING SETS ( (region, store), -- Subtotal per store within region (region), -- Subtotal per region () -- Grand total across all regions)ORDER BY region NULLS LAST, store NULLS LAST;
The empty parenthesis () defines the grand total level of aggregation. In rows representing region-level subtotals, the store column returns NULL. In the grand total row, both region and store return NULL. Consult the PostgreSQL grouping sets documentation for engine details.
ROLLUP: hierarchical subtotals and running totals
When your dimensions have a natural hierarchy, such as Year > Quarter > Month, or Country > State > City, ROLLUP produces hierarchical subtotals automatically. It calculates aggregates for each successive prefix of the column list, ending with the grand total.
ROLLUP syntax for temporal hierarchies
SELECT sale_year, sale_quarter, SUM(revenue) AS total_revenueFROM quarterly_salesGROUP BY ROLLUP (sale_year, sale_quarter)ORDER BY sale_year NULLS LAST, sale_quarter NULLS LAST;-- ROLLUP (sale_year, sale_quarter) generates 3 grouping sets:-- 1. (sale_year, sale_quarter) -> Detail quarter totals-- 2. (sale_year) -> Annual subtotal-- 3. () -> Grand total across all years
The order of columns in ROLLUP is significant. ROLLUP (A, B) computes (A, B), (A), and (). If you reverse the columns to ROLLUP (B, A), it computes (B, A), (B), and (), which creates different subtotals. In MySQL 8, this functionality is supported via GROUP BY A, B WITH ROLLUP per the MySQL group-by modifiers documentation.
CUBE: all possible cross-dimensional combinations
When dimensions are independent rather than hierarchical, such as Product Category and Customer Region, CUBE generates every mathematical permutation of grouping sets. If you specify CUBE (A, B), it computes (A, B), (A), and ().
CUBE syntax for cross-tabulation
SELECT category, region, SUM(revenue) AS total_revenueFROM product_salesGROUP BY CUBE (category, region)ORDER BY category NULLS LAST, region NULLS LAST;-- Generates 2^N grouping sets:-- (category, region), (category), (region), ()
Be cautious when adding columns to a CUBE clause. The number of grouping sets grows exponentially as two to the power of N ($2^N$). Specifying five columns produces 32 grouping sets, while ten columns produces 1,024 grouping sets, which can exhaust memory and CPU resources.
Distinguishing real NULLs from subtotal rows with GROUPING()
A common problem arises when a dimension column naturally contains NULL values. If a customer has no assigned region, region is NULL. How do you distinguish that customer from the grand total row where region is also NULL?
SQL solves this with the GROUPING() function. GROUPING(column) returns 1 if the column is currently aggregated in the current row, and 0 if the value represents an actual table row value.
Using GROUPING() to label subtotals cleanly
SELECT CASE WHEN GROUPING(region) = 1 THEN 'All Regions (Total)' ELSE COALESCE(region, 'Unassigned') END AS display_region, CASE WHEN GROUPING(store) = 1 THEN 'All Stores (Subtotal)' ELSE COALESCE(store, 'Direct Sales') END AS display_store, SUM(revenue) AS total_revenueFROM store_salesGROUP BY ROLLUP (region, store);
Actionable checklist for multi-level aggregation
Eliminate UNION ALL: audit reporting queries that stitch queries together with UNION ALL and replace with GROUPING SETS.
Pick the right clause: use ROLLUP for hierarchical data, CUBE for cross-tabulation, and GROUPING SETS for specific sets.
Use GROUPING(): wrap dimension columns with CASE and GROUPING() to provide clear labels and avoid ambiguous NULL values.
Limit CUBE dimensions: keep CUBE inputs to three or fewer columns to prevent combinatorial explosion.
Check NULLS LAST ordering: use ORDER BY column NULLS LAST to position subtotals cleanly at the end of groups.
Verify index support: confirm composite indexes exist on the grouping columns to accelerate the base aggregation pass.
Wrapping up
Mastering GROUPING SETS, ROLLUP, and CUBE enables you to deliver clean multi-dimensional reporting queries with minimal database workload. Single-pass aggregation eliminates redundant scans, protects query maintainability, and simplifies data pipeline architectures. Format your complex reporting queries with sqlfmt to guarantee clean indentation across your organization.