Site icon TestingDocs.com

MySQL GROUP BY ROLLUP Modifier

Overview

In this tutorial, we will learn and understand MySQL GROUP BY ROLLUP Modifier. The ROLLUP modifier can be used in the GROUP BY clause to produce multiple  levels of summary values.

Syntax

The simple syntax for the modifier is as follows:

mysql>SELECT <column_list>
->FROM <table_name>
->GROUP BY column WITH ROLLUP;

Example

In this example, we will use the Country table from the world MySQL database. Suppose that we need to generate population of each continent, as well as the total of the population on all continents.

We can use the WITH ROLLUP modifier. This enables you to use a single query to get both the detailed results as well as the total sum of all rows, eliminating the need for multiple queries.

mysql>SELECT Continent, SUM(Population) AS Continent_Population
->FROM Country
->GROUP BY Continent WITH ROLLUP;

+—————+———————-+
| Continent | Continent_Population |
+—————+———————-+
| Asia | 3705025700 |
| Europe | 730074600 |
| North America | 482993000 |
| Africa | 784475000 |
| Oceania | 30401150 |
| Antarctica | 0 |
| South America | 345780000 |
| NULL | 6078749450 |
+—————+———————-+
8 rows in set (0.00 sec)

Notice the NULL in the last row of the query result. The row contains the total sum of population
of all the continents. The ROLLUP modifier performs a super-aggregate operation for the last row.

Note that the ROLLUP doesn’t generate a sum of values that appear in the column. It applies the given aggregate function specified in the SELECT clause.

Let’s understand with a simple example. The following SQL query calculates the average population.

mysql> SELECT Continent, AVG(Population)
-> FROM Country
-> GROUP BY Continent WITH ROLLUP;
+—————+—————–+
| Continent | AVG(Population) |
+—————+—————–+
| Asia | 72647562.7451 |
| Europe | 15871186.9565 |
| North America | 13053864.8649 |
| Africa | 13525431.0345 |
| Oceania | 1085755.3571 |
| Antarctica | 0.0000 |
| South America | 24698571.4286 |
| NULL | 25434098.1172 |
+—————+—————–+
8 rows in set (0.00 sec)

The final last row contains the overall average and not the sum of the averages.

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/

For more information on MySQL Database:

https://www.mysql.com/

 

Exit mobile version