๐ข SQL ROLLUP โ Generate Subtotals and Grand Totals in SQL
The SQL
ROLLUPoperator helps you create hierarchical summaries by automatically calculating subtotals and grand totals in yourGROUP BYqueries.
Itโs widely used in reporting and dashboarding tasks where you want multiple levels of aggregation without writing multiple queries or using UNION ALL.
๐ What is SQL ROLLUP?
The ROLLUP operator is a grouping extension that generates aggregated rows at multiple levels of a hierarchy.
๐ฏ Use it when you want:
- Subtotals at intermediate levels
- A grand total for all data
- To avoid redundant
GROUP BY+UNIONcombinations
๐งพ Syntax of SQL ROLLUP
SELECT column1, column2, aggregate_function(column3)
FROM table_name
GROUP BY ROLLUP (column1, column2);
The order of columns in the ROLLUP matters โ it creates nested subtotals from left to right.
โ Example: Region and Yearly Sales with Subtotals
Letโs say you have the following sales table:
| region | year | amount |
|---|---|---|
| East | 2023 | 500 |
| East | 2024 | 700 |
| West | 2023 | 600 |
The following query uses ROLLUP to generate subtotals:
SELECT region, year, SUM(amount) AS total_sales
FROM sales
GROUP BY ROLLUP (region, year);
๐งพ Result:
| region | year | total_sales |
|---|---|---|
| East | 2023 | 500 |
| East | 2024 | 700 |
| East | NULL | 1200 |
| West | 2023 | 600 |
| West | NULL | 600 |
| NULL | NULL | 1800 |
๐ Interpretation:
- Rows with
NULLinyearโ subtotal by region - Row with
NULLin both โ grand total
๐ง How ROLLUP Works Internally
ROLLUP (A, B) generates:
- Group by A and B
- Group by A only (subtotal)
- Grand total (no grouping)
More columns = more subtotal levels.
๐ง Pro Tip: Use GROUPING() Function
You can distinguish real NULLs from subtotal NULLs using the GROUPING() function:
SELECT
region,
year,
SUM(amount) AS total_sales,
GROUPING(region) AS region_grouped,
GROUPING(year) AS year_grouped
FROM sales
GROUP BY ROLLUP (region, year);
This helps you format subtotal/grand total rows differently in your reports.
๐งฎ Real-World Use Cases for SQL ROLLUP
- ๐ Sales reports with region-wise and total summaries
- ๐งพ Expense summaries by department, then grand total
- ๐ฅ Employee headcounts per team, plus org-level totals
- ๐ฌ Inventory reports by category and product
๐ SQL ROLLUP vs GROUPING SETS vs CUBE
| Feature | ROLLUP | GROUPING SETS | CUBE |
|---|---|---|---|
| Subtotals | โ Yes (hierarchical) | โ Yes (custom) | โ Yes (all combinations) |
| Grand total | โ Yes | โ Optional | โ Yes |
| Custom logic | โ Fixed hierarchy | โ Fully customizable | โ Generates every possibility |
| Performance | โก Fast | โ Depends on sets | ๐ข Slow on large datasets |
๐ Summary
ROLLUPsimplifies hierarchical summarization- Use it to automatically generate subtotals and grand totals
- Combine it with
GROUPING()for formatting and clarity - Perfect for BI dashboards, sales summaries, and financial reports