๐งฎ ROLLUP, CUBE & GROUPING SETS
Reports often need totals at several levels at once: sales per city, per region, and a grand total. GROUPING SETS, ROLLUP and CUBE produce all of those levels in a single GROUP BY, instead of several queries glued together.
This tutorial assumes you know GROUP BY from GROUP BY & Aggregations.
1. Sample Data
sales holds six orders across two regions:
CREATE OR REPLACE TEMP VIEW sales AS
SELECT * FROM VALUES
('North', 'Delhi', 'Laptop', 1200),
('North', 'Delhi', 'Phone', 800),
('North', 'Jaipur', 'Laptop', 900),
('South', 'Chennai', 'Phone', 700),
('South', 'Chennai', 'Laptop', 1100),
('South', 'Bengaluru', 'Phone', 600)
AS sales(region, city, product, amount)
Later sections also use the employees view from the introduction, because it has an employee with a NULL department:
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
2. The Problem: Totals at Several Levels
Say you want sales per region and product, plus a total per region, plus a grand total. With plain GROUP BY, you need three queries combined with UNION ALL, using NULL as a placeholder for the "all" columns:
SELECT region, product, SUM(amount) AS total FROM sales GROUP BY region, product
UNION ALL
SELECT region, NULL, SUM(amount) FROM sales GROUP BY region
UNION ALL
SELECT NULL, NULL, SUM(amount) FROM sales
ORDER BY region, product
+------+-------+-----+
|region|product|total|
+------+-------+-----+
|NULL |NULL |5300 |
|North |NULL |2900 |
|North |Laptop |2100 |
|North |Phone |800 |
|South |NULL |2400 |
|South |Laptop |1100 |
|South |Phone |1300 |
+------+-------+-----+
It works, but it repeats the query three times, and every change has to be made in three places. The rest of this tutorial shows shorter ways to get exactly this result.
3. GROUPING SETS
GROUPING SETS lists the groupings you want, each in parentheses. () is the empty grouping, meaning the grand total:
SELECT region, product, SUM(amount) AS total
FROM sales
GROUP BY GROUPING SETS ((region, product), (region), ())
ORDER BY region, product
+------+-------+-----+
|region|product|total|
+------+-------+-----+
|NULL |NULL |5300 |
|North |NULL |2900 |
|North |Laptop |2100 |
|North |Phone |800 |
|South |NULL |2400 |
|South |Laptop |1100 |
|South |Phone |1300 |
+------+-------+-----+
The result is identical to the UNION ALL version. In each row, a column that is not part of that row's grouping is NULL. So North, NULL, 2900 reads as "North, all products".
GROUPING SETS is the most flexible of the three: you list exactly the combinations you want, and nothing else. ROLLUP and CUBE are shortcuts for common lists.
4. ROLLUP: Totals Along a Hierarchy
Many columns form a hierarchy: region contains cities, year contains months. ROLLUP produces totals for each level of the hierarchy, from the most detailed down to the grand total:
SELECT region, city, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP(region, city)
ORDER BY region, city
+------+---------+-----+
|region|city |total|
+------+---------+-----+
|NULL |NULL |5300 |
|North |NULL |2900 |
|North |Delhi |2000 |
|North |Jaipur |900 |
|South |NULL |2400 |
|South |Bengaluru|600 |
|South |Chennai |1800 |
+------+---------+-----+
ROLLUP(region, city) is shorthand for GROUPING SETS ((region, city), (region), ()). You get each city, each region's subtotal, and the grand total of 5300.
| You write | Spark computes the groupings |
|---|---|
ROLLUP(a, b) | (a, b), (a), () |
ROLLUP(a, b, c) | (a, b, c), (a, b), (a), () |
The column order matters. ROLLUP(region, city) gives region subtotals; ROLLUP(city, region) would give city subtotals, which is meaningless here because each city is in one region. Put the broadest level first.
Spark also accepts the older form GROUP BY region, city WITH ROLLUP, which means the same thing.
5. CUBE: Every Combination
CUBE produces totals for every combination of the listed columns. Use it when the columns are independent, like region and product, and you want to slice by either one:
SELECT region, product, SUM(amount) AS total
FROM sales
GROUP BY CUBE(region, product)
ORDER BY region, product
+------+-------+-----+
|region|product|total|
+------+-------+-----+
|NULL |NULL |5300 |
|NULL |Laptop |3200 |
|NULL |Phone |2100 |
|North |NULL |2900 |
|North |Laptop |2100 |
|North |Phone |800 |
|South |NULL |2400 |
|South |Laptop |1100 |
|South |Phone |1300 |
+------+-------+-----+
Compared with the ROLLUP-style result in section 3, CUBE adds the rows where region is NULL but product is not: total Laptop sales (3200) and total Phone sales (2100) across all regions.
| You write | Spark computes the groupings | Number of groupings |
|---|---|---|
CUBE(a, b) | (a, b), (a), (b), () | 4 |
CUBE(a, b, c) | all subsets of a, b, c | 8 |
With n columns, CUBE computes 2^n groupings, so it grows fast. Stick to a handful of columns.
6. Real NULLs vs Subtotal NULLs
Subtotal rows use NULL to mean "all values". But what if the data itself contains NULL? In employees, Grace has no department. Watch what ROLLUP does:
SELECT dept, COUNT(*) AS headcount, SUM(salary) AS total_salary
FROM employees
GROUP BY ROLLUP(dept)
ORDER BY dept
+-----------+---------+------------+
|dept |headcount|total_salary|
+-----------+---------+------------+
|NULL |7 |487000 |
|NULL |1 |45000 |
|Engineering|3 |259000 |
|Marketing |1 |58000 |
|Sales |2 |125000 |
+-----------+---------+------------+
There are now two rows with a NULL department: one is Grace's group (1 person), the other is the grand total (7 people). Looking at dept alone, you cannot tell them apart.
The GROUPING(column) function solves this. It returns 1 when the column was rolled up (the row is a subtotal for that column) and 0 when the value is a real group value, even a real NULL:
SELECT dept,
GROUPING(dept) AS is_total,
COUNT(*) AS headcount,
SUM(salary) AS total_salary
FROM employees
GROUP BY ROLLUP(dept)
ORDER BY is_total, dept
+-----------+--------+---------+------------+
|dept |is_total|headcount|total_salary|
+-----------+--------+---------+------------+
|NULL |0 |1 |45000 |
|Engineering|0 |3 |259000 |
|Marketing |0 |1 |58000 |
|Sales |0 |2 |125000 |
|NULL |1 |7 |487000 |
+-----------+--------+---------+------------+
Grace's row has is_total = 0: it is a real group whose value is NULL. The grand total has is_total = 1.
7. Labelling Subtotal Rows
Raw NULLs are confusing in a report. Use GROUPING() inside a CASE to give each kind of row a clear label:
SELECT CASE
WHEN GROUPING(dept) = 1 THEN 'All departments'
WHEN dept IS NULL THEN 'No department'
ELSE dept
END AS department,
COUNT(*) AS headcount,
SUM(salary) AS total_salary
FROM employees
GROUP BY ROLLUP(dept)
ORDER BY grouping_id(), department
+---------------+---------+------------+
|department |headcount|total_salary|
+---------------+---------+------------+
|Engineering |3 |259000 |
|Marketing |1 |58000 |
|No department |1 |45000 |
|Sales |2 |125000 |
|All departments|7 |487000 |
+---------------+---------+------------+
Sorting by grouping_id() first puts the detail rows on top and the grand total at the bottom, where readers expect it. With a single rolled-up column, grouping_id() is the same as GROUPING(dept); section 8 explains it in full. Writing ORDER BY GROUPING(dept) here fails in Spark 3.5 with an unresolved-column error, because dept is not in the SELECT list (it was replaced by the department label). grouping_id() takes no column, so it sorts without that problem.
Common mistake: Labelling totals with
COALESCE(dept, 'Total'). It turns everyNULLinto "Total", so Grace's department would also be called "Total", and the report would show two total rows. Always useGROUPING()to detect subtotal rows.
8. GROUPING_ID for Several Columns
With two or more columns, calling GROUPING() on each one gets long. grouping_id() combines them into one number. Each rolled-up column sets a bit, with the first column as the highest bit:
region rolled up | city rolled up | grouping_id() | Row type |
|---|---|---|---|
| No | No | 0 | City detail |
| No | Yes | 1 | Region subtotal |
| Yes | Yes | 3 | Grand total |
This makes it easy to label the level of each row, or to keep only certain levels:
SELECT region,
city,
grouping_id() AS gid,
CASE grouping_id()
WHEN 0 THEN 'city'
WHEN 1 THEN 'region subtotal'
WHEN 3 THEN 'grand total'
END AS level,
SUM(amount) AS total
FROM sales
GROUP BY ROLLUP(region, city)
ORDER BY gid, region, city
+------+---------+---+---------------+-----+
|region|city |gid|level |total|
+------+---------+---+---------------+-----+
|North |Delhi |0 |city |2000 |
|North |Jaipur |0 |city |900 |
|South |Bengaluru|0 |city |600 |
|South |Chennai |0 |city |1800 |
|North |NULL |1 |region subtotal|2900 |
|South |NULL |1 |region subtotal|2400 |
|NULL |NULL |3 |grand total |5300 |
+------+---------+---+---------------+-----+
To keep only the subtotals and the grand total, add HAVING grouping_id() > 0:
SELECT region, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP(region, city)
HAVING grouping_id() > 0
ORDER BY grouping_id(), region
+------+-----+
|region|total|
+------+-----+
|North |2900 |
|South |2400 |
|NULL |5300 |
+------+-----+
9. Which One Should You Use?
| Need | Use |
|---|---|
| Totals along a hierarchy (region, then city) | ROLLUP(region, city) |
| Totals for every combination of independent columns | CUBE(region, product) |
| A specific list of groupings, nothing more | GROUPING SETS (...) |
Tell real NULLs from subtotal rows | GROUPING(col) or grouping_id() |
All three compute every grouping in one query over the same input, which is shorter to write and usually cheaper than a UNION ALL of separate GROUP BY queries that each read the table again.
10. Try It in the Online Compiler
Copy this into the PySpark Online Compiler. Each spark.sql() call holds one statement:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL Grouping Sets").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW sales AS
SELECT * FROM VALUES
('North', 'Delhi', 'Laptop', 1200),
('North', 'Delhi', 'Phone', 800),
('North', 'Jaipur', 'Laptop', 900),
('South', 'Chennai', 'Phone', 700),
('South', 'Chennai', 'Laptop', 1100),
('South', 'Bengaluru', 'Phone', 600)
AS sales(region, city, product, amount)
""")
# City totals, region subtotals and a grand total
spark.sql("""
WITH totals AS (
SELECT region, city,
GROUPING(region) AS g_region,
GROUPING(city) AS g_city,
SUM(amount) AS total
FROM sales
GROUP BY ROLLUP(region, city)
)
SELECT CASE WHEN g_region = 1 THEN 'All regions' ELSE region END AS region,
CASE WHEN g_city = 1 THEN 'All cities' ELSE city END AS city,
total
FROM totals
ORDER BY g_region, region, g_city, city
""").show(truncate=False)
# Every combination of region and product
spark.sql("""
SELECT region, product, SUM(amount) AS total
FROM sales
GROUP BY CUBE(region, product)
ORDER BY region, product
""").show(truncate=False)
Summary
GROUPING SETS ((a, b), (a), ())computes several groupings in one query.()is the grand total.ROLLUP(a, b)is a shortcut for a hierarchy:(a, b),(a),(). Put the broadest column first.CUBE(a, b)computes every combination:(a, b),(a),(b),().- In subtotal rows, the rolled-up columns are
NULL.GROUPING(col)returns 1 for those rows, which tells them apart from realNULLvalues. grouping_id()packs theGROUPING()bits of all columns into one number, handy for labels andHAVINGfilters.
Next, you will learn PIVOT and UNPIVOT to turn rows into columns and back.