Interview Q&A / SQL & DBMS

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What does GROUP BY ROLLUP do?

SHORT ANSWER

ROLLUP adds subtotal and grand-total rows to a grouped result. For GROUP BY ROLLUP(a, b) you get rows for (a, b), then a subtotal per a, then one grand total, with NULL marking the rolled-up columns.

Explain it simply

A shop owner wants a sales sheet by city and product, with a subtotal line after each city and a grand total at the bottom. ROLLUP produces those extra lines automatically instead of running several queries and stacking them.

Example

Using the sales data of Pune-Tea 250, Pune-Coffee 200, Delhi-Tea 80:

sql
-- PostgreSQL, Oracle, SQL Server
SELECT city, product, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP (city, product);
-- MySQL: GROUP BY city, product WITH ROLLUP
cityproducttotal
DelhiTea80
DelhiNULL80
PuneCoffee200
PuneTea250
PuneNULL450
NULLNULL530

The NULLs mean "all products" or "all cities". If your real data also has NULLs, use GROUPING(city), which returns 1 on a rollup row, to tell them apart.

The hierarchy matters: ROLLUP(city, product) gives subtotals by city, not by product. CUBE gives subtotals for every combination.

What to say in the interview

"ROLLUP gives hierarchical subtotals and a grand total in one pass. NULL in a column marks a rolled-up level, and GROUPING() distinguishes it from real NULLs."

#sql#group-by#rollup#reporting

Related questions

Practise more SQL & DBMS questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open SQL & DBMS quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.