
MySQL ROLLUP
The MySQL ROLLUP
is a modifier that is used with the GROUP BY
clause to generate subtotals and grand totals in the result set of a query. It is particularly useful in generating summary reports or aggregating data at multiple levels of hierarchy within a table.
The ROLLUP
modifier creates a result set that includes subtotals at different levels of grouping, including the grand total.
The basic syntax for using ROLLUP
is as follows:
SELECT column1, column2, ..., aggregate_function(column)
FROM table
GROUP BY column1, column2, ..., ROLLUP(column);
Here’s how it works:
- You specify the columns you want to group by in the
GROUP BY
clause. - You include the
ROLLUP
modifier for one of the columns. - The query will generate subtotals and a grand total based on the columns specified in the
ROLLUP
clause.
Let’s illustrate this with an example. Suppose you have a sales table with columns Region
, Country
, and SalesAmount
, and you want to generate a report that includes subtotals at both the country and region levels, as well as a grand total. You can use the ROLLUP
modifier like this:
SELECT Region, Country, SUM(SalesAmount) AS TotalSales
FROM Sales
GROUP BY Region, Country WITH ROLLUP;
The result will include rows that provide subtotals for each region and each region/country combination, as well as a grand total at the end.
Here’s a simplified example of the result:
+---------+-----------+-------------+
| Region | Country | TotalSales |
+---------+-----------+-------------+
| North | USA | 10000 |
| North | Canada | 5000 |
| North | NULL | 15000 | -- Subtotal for North
| South | Brazil | 8000 |
| South | Argentina | 3000 |
| South | NULL | 11000 | -- Subtotal for South
| NULL | NULL | 26000 | -- Grand Total
+---------+-----------+-------------+
In this result set, you can see subtotals for each region and a grand total, thanks to the ROLLUP
modifier.
You can use the ROLLUP
modifier with more than one column, allowing you to generate subtotals and grand totals at multiple levels in your data hierarchy. It’s a powerful feature for creating summary reports with aggregated data.