T
Tech Town
Log InSign Up Free
← Back to Blog

June 17, 2025 · admin

ROLLUP

๐Ÿ”ข SQL ROLLUP โ€“ Generate Subtotals and Grand Totals in SQL

The SQL ROLLUP operator helps you create hierarchical summaries by automatically calculating subtotals and grand totals in your GROUP BY queries.

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 + UNION combinations

๐Ÿงพ 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:

regionyearamount
East2023500
East2024700
West2023600

The following query uses ROLLUP to generate subtotals:

SELECT region, year, SUM(amount) AS total_sales
FROM sales
GROUP BY ROLLUP (region, year);

๐Ÿงพ Result:

regionyeartotal_sales
East2023500
East2024700
EastNULL1200
West2023600
WestNULL600
NULLNULL1800

๐Ÿ“Œ Interpretation:

  • Rows with NULL in year โ†’ subtotal by region
  • Row with NULL in both โ†’ grand total

๐Ÿง  How ROLLUP Works Internally

ROLLUP (A, B) generates:

  1. Group by A and B
  2. Group by A only (subtotal)
  3. 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

FeatureROLLUPGROUPING SETSCUBE
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

  • ROLLUP simplifies 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