When we use grouping or aggregate functions, we can use ROLLUP operator to add one or more summary rows into the result set.
ROLLUP operator is available in SQL and MySQL both with slightly different syntax.
ROLLUP Syntax in SQL:
SELECT column_1, column_2, aggregate_function(column_3) FROM table_name GROUP BY ROLLUP (column_1,column_2);
ROLLUP Syntax in MySQL:
SELECT column_1, column_2, aggregate_function(column_3) FROM table_name GROUP BY column_1,column_2 WITH ROLLUP;
Let's look at some examples to understand it better.
//Query in MySQL SELECT seller_id, COUNT(*) AS number_of_invoice, SUM(invoice_total) AS invoice_total FROM invoices GROUP BY seller_id WITH ROLLUP; //Query in SQL SELECT seller_id, COUNT(*) AS number_of_invoice, SUM(invoice_total) AS invoice_total FROM invoices GROUP BY ROLLUP(seller_id);
In this example, we are using ROLLUP with a single column. In invoices are grouped by seller id in the query. Also, we are calculating number of invoice and sum of invoice total for each seller.
Checkout the DEMO link given at the end of this article.
Look at the last row. That's a summary row. It's added because of ROLLUP operator in Group By. It summarizes all the aggregate columns in the last row.
So, in the result set the number_of_invoice and invoice_total columns are being summarized by the ROLLUP operator.
Why there is no value in seller_id column in the summarized row?
That's because it can't be summarized. You'll see null value in SQL and empty rows in MySQL.
Let's take a look at another query.
//Query in MySQL SELECT seller_state, seller_city, COUNT(*) AS total_sellers FROM sellers WHERE seller_state IN ('FL','IN') GROUP BY seller_state, seller_city WITH ROLLUP; //Query in SQL â€‹â€‹â€‹â€‹â€‹â€‹â€‹ SELECT seller_state, seller_city, COUNT(*) AS total_sellers FROM sellers WHERE seller_state IN ('FL','IN') GROUP BY ROLLUP(seller_state, seller_city) ORDER BY seller_name,seller_city; <-- you can use Order by in SQL after ROLLUP
The query above uses 2 columns with ROLLUP operator.
This query groups all the sellers by state and then city. It also counts number of sellers in each group.
You'll see additional rows in the result set. That's because the summary rows are added for each state and a final summary row as well.
You can also use ORDER BY with ROLLUP in SQL. MySQL doesn't allow to do that.
To deal with null values, you can use the GROUPING function. I'll discuss about it in future article.
database ROLL UP sql operators sql query