01 / 21

SQL Grouping Sets

Learn how to produce multiple levels of aggregation in a single query using GROUPING SETS, ROLLUP, and CUBE.

SQL

What Is Aggregation?

When you use GROUP BY in SQL, you collapse many rows into summary rows. Functions like SUM, COUNT, and AVG compute a single value for each group.

But what if you need both levels in the same result: totals per region and totals per region-product? That is exactly the problem GROUPING SETS solves.

The Multi-Level Problem

Without GROUPING SETS, you would write separate queries for each grouping level and combine them with UNION ALL:

SELECT region, product, SUM(sales) FROM orders GROUP BY region, product UNION ALL SELECT region, NULL, SUM(sales) FROM orders GROUP BY region;

Introducing GROUPING SETS

GROUPING SETS is a clause inside GROUP BY that lets you list multiple grouping combinations. The database computes all of them in one pass over the data.

SELECT region, product, SUM(sales) FROM orders GROUP BY GROUPING SETS ( (region, product), (region), () );

How It Works Visually

orders table region | product | sales East | Widget | 100 East | Gadget | 200 West | Widget | 150 West | Gadget | 250 GROUPING SETS (region, product) (region) () Detail Level East | Widget | 100 East | Gadget | 200 West | Widget | 150 West | Gadget | 250 Region Level East | NULL | 300 West | NULL | 400 Grand Total NULL | NULL | 700

The Formal Syntax

SELECT col1, col2, ..., AGG(value) FROM table GROUP BY GROUPING SETS ( (col1, col2), -- detail level (col1), -- subtotal by col1 () -- grand total );
1
Each parenthesized group defines a separate aggregation level.
2
Columns not in a set appear as NULL in that set's rows.
3
The empty set () produces one grand-total row with all grouping columns NULL.

ROLLUP vs CUBE vs GROUPING SETS

Feature GROUPING SETS ROLLUP CUBE
You choose sets ✓ Explicit Automatic hierarchy Automatic all combos
For (a, b) You list each set (a,b), (a), () (a,b), (a), (b), ()
Number of sets Exactly what you list \( n + 1 \) \( 2^n \)
Best for Custom combos Hierarchical totals Cross-tab reports

Shortcut: ROLLUP

ROLLUP(a, b) is equivalent to writing out a hierarchical grouping sets list. It peels off columns right to left:

-- These two are identical: GROUP BY ROLLUP(region, product) GROUP BY GROUPING SETS ( (region, product), (region), () )

Shortcut: CUBE

CUBE(a, b) generates every possible combination of the listed columns, including the empty set:

-- These two are identical: GROUP BY CUBE(region, product) GROUP BY GROUPING SETS ( (region, product), (region), (product), () )

The GROUPING() Function

When a column is NULL, how do you tell the difference between a real NULL in the data and a grouping-set NULL? Use the GROUPING() function.

SELECT region, product, SUM(sales) AS total, GROUPING(region) AS is_region_agg, GROUPING(product) AS is_product_agg FROM orders GROUP BY ROLLUP(region, product);

How to Apply Grouping Sets

1
Identify your aggregation levels. Which combinations of columns do your report readers need?
2
Choose the right tool. Hierarchical? Use ROLLUP. All combos? Use CUBE. Custom? Use GROUPING SETS.
3
Write the SELECT. List all grouping columns plus your aggregate functions.
4
Add GROUPING() if needed. Use it to label or filter aggregated vs. detail rows.
5
Order the results. Use ORDER BY with GROUPING() to place totals logically.

Example 1: Sales Report

SELECT region, product, SUM(sales) AS total FROM orders GROUP BY GROUPING SETS ( (region, product), (region), () ) ORDER BY region, product;
regionproducttotal
EastGadget200
EastWidget100
EastNULL300
WestGadget250
WestWidget150
WestNULL400
NULLNULL700

Example 2: ROLLUP for Dates

SELECT year, quarter, month, SUM(revenue) AS total_rev FROM financials GROUP BY ROLLUP(year, quarter, month);

This produces four aggregation levels automatically:

(year, quarter, month)
Monthly detail
(year, quarter)
Quarterly subtotals
(year)
Yearly subtotals
()
Grand total

Example 3: CUBE Cross-Tab

SELECT dept, gender, AVG(salary) AS avg_sal FROM employees GROUP BY CUBE(dept, gender);
deptgenderavg_sal
EngF95000
EngM92000
EngNULL93500
SalesF78000
SalesM81000
SalesNULL79500
NULLF86500
NULLM86500
NULLNULL86500

Common Mistakes

✕ Confusing NULL Sources
Treating aggregation NULLs as missing data. Use GROUPING() to distinguish them.
✕ Wrong Shortcut
Using ROLLUP when you need all combinations (that's CUBE), or CUBE when you only need a hierarchy (that's ROLLUP).
✕ Column Order in ROLLUP
ROLLUP(a, b) is NOT the same as ROLLUP(b, a). The order defines the hierarchy.

Summary at a Glance

Concept Key Idea When to Use
GROUPING SETS List exact combos you want Custom reporting needs
ROLLUP Hierarchical: peels right to left Date or geographic hierarchies
CUBE All \( 2^n \) combinations Cross-tab / pivot reports
GROUPING() Returns 1 if NULL from aggregation Disambiguating NULL values
Empty set () Grand total row Overall summary line

Question 1 of 5

What does GROUPING SETS allow you to do in a single query?

Question 2 of 5

Which of the following is equivalent to GROUP BY ROLLUP(a, b)?

Question 3 of 5

How many grouping sets does CUBE(x, y, z) produce?

Question 4 of 5

What does GROUPING(column) return when the NULL in that column is caused by aggregation?

Question 5 of 5

What does the empty set () inside GROUPING SETS produce?