Skip to content
Tutor Furycat

Using ROLLUP in MySQL to Summarize Data

Using ROLLUP in MySQL to Summarize Data
In this article

The WITH ROLLUP modifier in MySQL extends the standard GROUP BY clause to generate higher-level summary rows, including subtotals and grand totals, in a single query. It calculates aggregations from right to left across grouping columns, outputting hierarchical super-aggregate rows marked by NULL values representing summarized sets.

SELECT department, team, SUM(sales) AS total_sales FROM sales_records GROUP BY department, team WITH ROLLUP;

How the WITH ROLLUP Modifier Works in MySQL

In relational database reporting, business intelligence workflows frequently require multi-tiered reporting. For instance, an operations team might need sales grouped by country, region, and city, alongside subtotals for each country and region, plus a grand total across all operations.

Historically, achieving this required executing separate aggregation queries and binding them together using UNION ALL. This approach is computationally inefficient because the database engine must scan and group the base data multiple times. The WITH ROLLUP modifier solves this problem at the database engine level by adding super-aggregate summary operations into a single execution pass.

When you append WITH ROLLUP to a GROUP BY clause, MySQL generates extra rows representing higher-level summaries. For a grouping specification with $n$ dimensions—such as GROUP BY col1, col2, col3 WITH ROLLUP—MySQL produces $n + 1$ levels of aggregation. It evaluates combinations by removing expressions progressively from right to left:

  1. (col1, col2, col3): The most granular level of aggregation.
  2. (col1, col2): The first subtotal level, where col3 is represented as NULL.
  3. (col1): The second subtotal level, where both col2 and col3 evaluate to NULL.
  4. (): The grand total row, where all grouped columns evaluate to NULL.

Because MySQL processes the hierarchy strictly from right to left, the column order in your GROUP BY clause determines your aggregation hierarchy. Placing categories before subcategories produces category subtotals; reversing that order produces subcategory subtotals across categories.

Single-Column vs. Multi-Column Rollups

The behavior and output layout of WITH ROLLUP vary significantly depending on whether your query groups by one column or multiple columns.

Single-Column Aggregation

In single-column aggregation, WITH ROLLUP produces one additional record: the grand total across the entire result set.

SELECT product_category, COUNT(*) AS total_items, SUM(inventory_value) AS category_value FROM warehouse_inventory GROUP BY product_category WITH ROLLUP;

In this output, standard rows display the individual product_category names alongside their respective counts and sums. The final row displays NULL in the product_category column, representing the cumulative sum and count across all categories.

Multi-Column Hierarchical Aggregation

When aggregating over multiple columns, the hierarchy becomes evident. Consider a retail sales dataset tracked by store_region, store_state, and store_city:

SELECT store_region, store_state, store_city, SUM(revenue) AS total_revenue FROM regional_sales GROUP BY store_region, store_state, store_city WITH ROLLUP;

This multi-column query produces an output structured along administrative boundaries:

  • Regular rows contain values for region, state, and city.
  • Subtotal rows for each state contain values for store_region and store_state, with NULL for store_city.
  • Subtotal rows for each region contain a value for store_region, with NULL for both store_state and store_city.
  • The final row contains NULL across all three grouping columns, representing global total revenue.
How to Summarize Excel Data Without Pivot Tables: 4 Faster Ways (2026)
How to Summarize Excel Data Without Pivot Tables: 4 Faster Ways (2026)

Distinguishing Stored NULLs from Aggregate NULLs Using GROUPING()

A common challenge when working with WITH ROLLUP arises when the underlying data contains genuine NULL values. If an employee record has no assigned region (evaluating to NULL), standard query output makes it impossible to distinguish whether a row represents sales for unassigned regions or a subtotal across all regions.

MySQL 8.0 resolved this ambiguity by introducing the standard SQL GROUPING() function. The GROUPING() function takes a column reference as an argument and returns:

  • 0 if the NULL value in the result represents a real, stored value from the underlying table.
  • 1 if the NULL was generated by MySQL as a super-aggregate summary row.

Applying GROUPING() with Descriptive Labels

Using GROUPING() inside conditional expressions like IF() or CASE allows you to replace aggregate NULL values with readable labels without altering stored NULL records:

SELECT IF(GROUPING(store_region) = 1, 'All Regions', store_region) AS region, IF(GROUPING(store_state) = 1, 'Region Subtotal', store_state) AS state, SUM(revenue) AS revenue FROM regional_sales GROUP BY store_region, store_state WITH ROLLUP;

This ensures that the output explicitly differentiates between missing source data and calculated reporting subtotals, which prevents data misinterpretation in client applications or automated reporting pipelines.

Sorting and Pagination Constraints with ROLLUP

The internal execution architecture of WITH ROLLUP introduces constraints regarding ordering and pagination that developers must address directly.

The ORDER BY Conflict

In modern MySQL (version 8.0 and later), combining ORDER BY with WITH ROLLUP directly within the same query block raises an error (ERROR 1221 (HY000): Incorrect usage of CUBE/ROLLUP and ORDER BY). This restriction exists because an arbitrary sort order breaks the physical grouping hierarchy that makes the rolled-up rows logically coherent.

For example, if you sort strictly by revenue DESC, the grand total row would float to the top or scatter between intermediate groups, detaching subtotals from their parent records.

To sort a rolled-up dataset while preserving hierarchical placement, wrap the aggregation in a common table expression (CTE) or derived table subquery:

WITH RankedReport AS ( SELECT store_region, store_state, SUM(revenue) AS total_revenue, GROUPING(store_region) AS grp_region, GROUPING(store_state) AS grp_state FROM regional_sales GROUP BY store_region, store_state WITH ROLLUP ) SELECT IF(grp_region = 1, 'Grand Total', store_region) AS region, IF(grp_state = 1, 'Subtotal', store_state) AS state, total_revenue FROM RankedReport ORDER BY grp_region ASC, region ASC, grp_state ASC, total_revenue DESC;

By sorting on the GROUPING() indicator flags first, you keep detailed rows together, keep subtotals pinned directly beneath their corresponding children, and keep the grand total predictably anchored at the end.

Filtering with HAVING

The HAVING clause operates on the output of the grouping operation, including generated rollup rows. If you apply a standard filter like HAVING total_revenue > 50000, MySQL filters out individual store rows that fall below that threshold, but retains subtotal rows if the aggregate sum passes the condition.

If you want to filter out rolled-up rows while retaining low-level details, check the GROUPING() state within the HAVING clause.

Comparing WITH ROLLUP to Alternative Aggregation Patterns

Choosing between WITH ROLLUP, multiple UNION ALL statements, SQL window functions, or client-side calculation depends on the volume of data, database indexing, and downstream consumption requirements.

Aggregation Technique Query Complexity Execution Passes Subtotals Support Best Use Case
WITH ROLLUP Low Single pass Hierarchical only Fast server-side reports, console exports, and direct aggregation exports.
UNION ALL Blocks High Multiple passes Any custom grouping combination Disjoint aggregations where hierarchies do not match a right-to-left layout.
Window Functions (SUM() OVER) Medium Single or dual pass Non-hierarchical; retains row details Retaining individual raw line items alongside running or partition totals.
Application Layer Aggregation Minimal SQL Single raw pass Arbitrary / Complex Interactive user interfaces with dynamic UI foldering, sorting, and drill-down.

While UNION ALL allows flexible restructuring of grouped data, it scales poorly. For three levels of grouping over millions of records, UNION ALL requires three index scans or temporary tables. WITH ROLLUP computes intermediate states in a single scan while writing to the output stream.

Practical Example: Generating Sales Summaries

To illustrate the complete workflow, consider an e-commerce platform analyzing order metrics across product lines and distribution channels.

Source Schema and Data

CREATE TABLE order_items ( order_id INT AUTO_INCREMENT PRIMARY KEY, sales_channel VARCHAR(30), product_line VARCHAR(50), quantity_sold INT, line_total DECIMAL(10,2) ); INSERT INTO order_items (sales_channel, product_line, quantity_sold, line_total) VALUES ('Direct', 'Electronics', 10, 5000.00), ('Direct', 'Apparel', 25, 1250.00), ('Wholesale', 'Electronics', 50, 22500.00), ('Wholesale', 'Apparel', 100, 4000.00), ('Direct', 'Electronics', 5, 2500.00);

Analytical Summary Query

We run a summary report showing units sold, revenue, and average transaction size, applying GROUPING() to keep data labels clean:

SELECT CASE WHEN GROUPING(sales_channel) = 1 THEN 'Company Total' ELSE sales_channel END AS channel, CASE WHEN GROUPING(product_line) = 1 AND GROUPING(sales_channel) = 0 THEN 'Channel Subtotal' WHEN GROUPING(product_line) = 1 AND GROUPING(sales_channel) = 1 THEN 'Global Product Total' ELSE product_line END AS line, SUM(quantity_sold) AS total_units, SUM(line_total) AS total_revenue, ROUND(AVG(line_total), 2) AS avg_line_value FROM order_items GROUP BY sales_channel, product_line WITH ROLLUP;

Result Interpretation

The query outputs clean, labeled records without ambiguous NULL fields:

  • Direct / Apparel: Detailed line items showing 25 units and $1,250.00 revenue.
  • Direct / Electronics: Detailed line items showing 15 units and $7,500.00 revenue.
  • Direct / Channel Subtotal: Combined performance for Direct sales (40 units, $8,750.00).
  • Wholesale / Apparel: Detailed line items showing 100 units and $4,000.00 revenue.
  • Wholesale / Electronics: Detailed line items showing 50 units and $22,500.00 revenue.
  • Wholesale / Channel Subtotal: Combined performance for Wholesale sales (150 units, $26,500.00).
  • Company Total / Global Product Total: Overall summary across all channels and products (190 units, $35,250.00).

Performance Considerations and Index Usage

Using WITH ROLLUP does not introduce heavy processing penalties compared to a plain GROUP BY, but indexing efficiency directly affects how the engine computes intermediate totals.

Optimizing with Composite Indexes

MySQL can evaluate GROUP BY ... WITH ROLLUP using an index scan if the indexed columns match the grouping columns from left to right.

If your query groups by sales_channel, product_line, a composite index configured as:

ALTER TABLE order_items ADD INDEX idx_channel_product (sales_channel, product_line);

allows MySQL to perform an index-driven group aggregation. The storage engine traverses the index leaves in sequential order. Because data is already pre-sorted by the grouping hierarchy, MySQL generates aggregate and super-aggregate subtotals on the fly as it transitions across distinct channel values, avoiding temporary tables and filesorts.

Temporary Table Overhead

If no covering or prefixed composite index exists, MySQL creates an internal temporary disk or in-memory table to group rows, then scans that temporary table to calculate the rollup summaries.

You can check whether your query is using temporary storage by running EXPLAIN:

EXPLAIN SELECT sales_channel, product_line, SUM(line_total) FROM order_items GROUP BY sales_channel, product_line WITH ROLLUP;

If the Extra column displays Using temporary; Using filesort, the aggregation relies on intermediate disk or memory buffers. To optimize this, design composite indexes that match your reporting hierarchies.

Frequently Asked Questions

What is the primary difference between ROLLUP and CUBE in SQL?

MySQL supports WITH ROLLUP, but it does not support CUBE. ROLLUP generates hierarchical subtotals strictly from right to left based on the order of columns in the GROUP BY clause ($n + 1$ combinations). In contrast, CUBE generates subtotals for every possible mathematical permutation of the specified columns ($2^n$ combinations). To replicate CUBE functionality in MySQL, you must write separate GROUP BY ... WITH ROLLUP queries and join them using UNION ALL.

Can you use LIMIT with WITH ROLLUP?

Yes, you can use LIMIT with WITH ROLLUP, but it limits the total output rows returned by the query, not just detailed or subtotal rows. Applying LIMIT 5 returns the first five rows of the output stream. Depending on where the subtotal rows fall, pagination with LIMIT and OFFSET can push the grand total or intermediate subtotals onto later pages, separating them from their underlying records. To control this, run the pagination on a derived query that sorts rows into a predictable hierarchy.

Why does ORDER BY return an error with WITH ROLLUP in modern MySQL?

MySQL 8.0 prohibits direct ORDER BY clauses alongside WITH ROLLUP to prevent confusing result sets. Because rollup operations generate subtotals inline with the grouped hierarchy, sorting by arbitrary metrics (such as SUM(column) DESC) would place subtotals out of order relative to their child rows. To sort results while keeping subtotals attached to their groups, wrap your query in a Common Table Expression (CTE) and sort by the grouping flags alongside the aggregate values.

Does WITH ROLLUP calculate DISTINCT aggregates properly?

Yes. Aggregations such as COUNT(DISTINCT customer_id) or SUM(DISTINCT rate) evaluate correctly inside WITH ROLLUP. For super-aggregate rows, MySQL evaluates the distinct constraint across the entire aggregate group rather than adding the pre-aggregated results of earlier lines. For example, if a customer bought items in two different subcategories within the same division, COUNT(DISTINCT customer_id) in the division subtotal row counts that customer once, not twice.

How does the HAVING clause treat rolled-up rows?

The HAVING clause filters result rows after aggregate calculations finish, which applies the filter to both standard grouped rows and rollup rows. If a subtotal row does not satisfy the condition in the HAVING clause, MySQL removes it from the final output. If you want to filter out low-volume child rows while keeping higher-level subtotals, check the GROUPING() state within the HAVING clause.

Implementation Checklist for Production Queries

Follow these steps when writing queries with WITH ROLLUP to avoid common sorting and performance issues:

  1. Order Columns Hierarchically: Place the highest-level grouping column first, followed by lower-level nested attributes (e.g., GROUP BY continent, country, city WITH ROLLUP).
  2. Handle NULL Values Explicitly: Wrap grouped columns in IF() or CASE statements using GROUPING() to differentiate real data from generated super-aggregate subtotals.
  3. Add Composite Indexes: Match the order of your GROUP BY columns in a multi-column index to help MySQL aggregate data without relying on temporary tables or filesorts.
  4. Isolate Sorting via CTEs: When reports require specific sorting rules, process the WITH ROLLUP calculation inside a Common Table Expression, then apply your ORDER BY logic in the outer query.
  5. Verify Execution Plans: Run EXPLAIN to confirm whether your query relies on Using temporary; Using filesort, and tune your indexes accordingly for large tables.

Sharing is caring