Mastering MySQL for Data AnalystsLesson 18 of 42
Lesson 18 of 42

Multi-Level Aggregations: WITH ROLLUP & GROUPING() in MySQL

Overview & Learning Objectives

Financial controllers and executives require reports that include both detailed breakdown categories and hierarchical subtotals and grand totals in a single query result. In MySQL, adding `WITH ROLLUP` to the `GROUP BY` clause automatically generates super-aggregate subtotal and grand total rows. To distinguish between natural data NULLs and generated subtotal rows, MySQL 8.0 provides the standard `GROUPING()` function.

  • Generate hierarchical subtotals and grand totals using `GROUP BY ... WITH ROLLUP`.
  • Distinguish generated subtotal rows from genuine data NULLs using the `GROUPING()` function.
  • Format executive summary matrices with clean subtotal label tags.

Industry Standard

Standard: Financial reporting pipelines at major banks use `WITH ROLLUP` to compute multi-tier departmental ledger subtotals in a single optimized database pass.

Real-World Example: ScoopCraft Regional Sales Subtotal Matrix

ScoopCraft accounting generates quarterly sales figures showing category subtotals and a final grand total row.

RegionProduct CategoryTotal Sales (₹)Row Type Identified by GROUPING()
SouthTubs₹450,000.00Detail Row (0, 0)
SouthCones₹280,000.00Detail Row (0, 0)
SouthAll Categories (Subtotal)₹730,000.00Regional Subtotal (0, 1)
Grand TotalAll Categories (Grand Total)₹1,850,000.00Grand Total (1, 1)

Syntax & Core SQL Implementation

-- Multi-level hierarchical aggregation with ROLLUP in MySQL 8.0
SELECT 
    IF(GROUPING(region), 'All Regions (Grand Total)', region) AS region_label,
    IF(GROUPING(category), 'All Categories (Subtotal)', category) AS category_label,
    ROUND(SUM(order_total), 2) AS total_sales,
    COUNT(order_id) AS total_orders
FROM orders
WHERE order_date >= '2026-01-01'
GROUP BY region, category WITH ROLLUP;

Parameters & Arguments Breakdown

  • WITH ROLLUP: Modifier appended to GROUP BY that generates hierarchical subtotal and grand total rows.
  • GROUPING(col): Returns 1 if the row represents an aggregate subtotal for that column, and 0 for standard detail rows.

Sample Walkthrough (Q&A)

Question: Why is GROUPING() necessary when working with WITH ROLLUP in MySQL?

SQL Pattern: GROUPING(category)

Result: Returns 1 for generated subtotal rows, and 0 for actual data rows

Explanation: ROLLUP inserts NULL into columns representing subtotals. If data already contains genuine NULL values, GROUPING() is the only way to reliably distinguish them.

Common Mistakes & Limitations

  • Using `ORDER BY` with `WITH ROLLUP` in older MySQL versions (in MySQL 8.0.12+, you can sort rollup outputs, but in older versions it caused syntax errors).
  • Confusing the hierarchy order: `GROUP BY A, B WITH ROLLUP` generates subtotals for A and a Grand Total, but NOT subtotals for B alone.

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • Order of columns in `GROUP BY col1, col2 WITH ROLLUP` matters: it rolls up from right to left (col2 subtotals within col1, then grand total).
  • Use `IF(GROUPING(col), "Subtotal", col)` to replace confusing empty NULL cells in executive Excel exports.