MySQL ROLLUP
The ROLLUP operator in MySQL is used with the GROUP BY clause to generate subtotals and grand totals for grouped data. It provides a convenient way to calculate cumulative totals and summarize results at multiple levels within a single query.
Key Features
- Subtotals: Provides subtotals for each group.
- Grand Total: Adds a row that shows the grand total for all groups.
- Works with GROUP BY: Used as part of the GROUP BY clause.
Syntax
column1, column2
: Columns to group by.aggregate_function(column3)
: Functions likeSUM
,COUNT
, etc., applied to the grouped data.WITH ROLLUP
: Generates subtotal and grand total rows.
Example Table
Table: sales
1. Basic ROLLUP Example
Calculate total sales for each product and a grand total:
Result
- The
NULL
in the product column represents the grand total.
2. ROLLUP with Multiple Columns
Generate subtotals by region, product, and grand total:
Result
NULL
inproduct
: Subtotal for each region.NULL
in bothregion
andproduct
: Grand total.
3. Filtering Out ROLLUP Rows
To exclude rows with NULL values (subtotal or grand total rows), use the HAVING
clause:
4. ROLLUP with Aliases
You can rename NULL
values in the results for better readability:
Result
5. Using ROLLUP with Multiple Aggregates
Calculate both the SUM and COUNT for each group:
Result
Performance Tips
Indexes:
- Ensure columns used in the GROUP BY clause are indexed for optimal performance.
Filtering with ROLLUP:
- Use HAVING or WHERE clauses to control the output rows.
Use Cases
Sales Reporting:
- Subtotals and grand totals by region, product, or other dimensions.
Inventory Management:
- Calculate stock levels and subtotals across categories.
Financial Summaries:
- Generate income and expense summaries for each department and overall.
Let me know if you need help with additional examples or queries!