mysql
  1. mysql-rollup

ROLLUP - (MySQL Misc)

In MySQL, ROLLUP is a modifier used with the GROUP BY clause to generate subtotals for each level of grouping. In this tutorial, we'll discuss how to use ROLLUP in MySQL.

Syntax

The basic syntax for using ROLLUP with the GROUP BY clause is as follows:

SELECT column1, column2, SUM(column3)
 FROM table_name
 GROUP BY column1, column2 WITH ROLLUP;

The ROLLUP modifier is placed at the end of the GROUP BY clause.

Example

Let's say we have a table called "sales" with the following data:

region city sales
East Boston 100
East Boston 150
East NYC 200
West LA 300
West SF 250

Now, let's say we want to display the sum of sales by region and city, as well as the total sum of sales for each region. We can use ROLLUP to achieve this:

SELECT region, city, SUM(sales)
FROM sales
GROUP BY region, city WITH ROLLUP;

This will produce the following output:

region city SUM(sales)
East Boston 250
East NYC 200
East NULL 450
West LA 300
West SF 250
West NULL 550
NULL NULL 1000

The NULL values represent the total sum of sales for each region and all regions combined.

Explanation

In the example above, we used ROLLUP with the GROUP BY clause to generate subtotals for each level of grouping. We grouped the data by region and city, and then used the ROLLUP modifier to generate subtotals for each region and all regions combined.

The NULL values represent the subtotals generated by ROLLUP.

Use

ROLLUP is useful for generating subtotals for each level of grouping in MySQL. It can make it easier to analyze data and identify patterns.

Important Points

  • ROLLUP can be useful for generating subtotals for each level of grouping in MySQL.
  • The NULL values produced by ROLLUP represent the subtotals generated.
  • ROLLUP can be used with multiple columns in the GROUP BY clause.

Summary

In this tutorial, we discussed how to use ROLLUP in MySQL to generate subtotals for each level of grouping. We covered the syntax, example, output, explanation, use, and important points of ROLLUP in MySQL. With this knowledge, you can now use ROLLUP in your MySQL queries to analyze data and identify patterns.

Published on: