GROUPING SETS and CUBE in SQL
GROUPING SETS lists several GROUP BY levels in one query; CUBE returns every combination of them.
ROLLUP
builds a hierarchy of subtotals: category, then category plus
supplier, then a grand total. But sometimes you want totals for two
dimensions independently: a breakdown by category and a separate
breakdown by supplier without the nested combinations.
GROUPING SETS
gives you exactly that control: you list each grouping level you want, and
the empty set
()
adds the grand total.
CUBE
is the shortcut for "every combination of these dimensions".
select region, product, sum(amount) as total
from sales
group by grouping sets ((region), (product), ())
-- ROLLUP(region, product) = a hierarchy of subtotals
-- CUBE(region, product) = every combination of subtotals Labeling the subtotal rows
On a per-supplier subtotal row there is no single category, so
category_name
comes back as
NULL. If source data can also contain real nulls,
coalesce()
alone cannot tell them apart. Use
grouping()
to identify generated subtotal rows before assigning labels such as "All
categories".
Schema · Garden Shop Tables · products, categories, suppliers 3 tables
One row per product, with price, cost, and inventory levels.
Lookup table of product categories.
One row per supplier. Some suppliers have no contact email.
In one query, count products by category, by supplier, and overall. Label the subtotal rows "All categories" and "All suppliers" so every row reads clearly, and sort by category, then supplier.
Run your query to inspect the result.
Expected answer
- Columns: category, supplier, product_count.
- Eight per-category rows, five per-supplier rows, and one grand-total row (14 rows).
- ROLLUP is a hierarchy; GROUPING SETS lets you pick independent levels, and CUBE returns every combination.
Related
COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING.
COUNT, SUM, AVG, GROUP BY, and HAVING.
Practice aggregate reports, HAVING, and answer shape.
Avoid truncating fractional results.
Filter groups with HAVING, rows with WHERE.
Searched and simple CASE patterns.