Skip to content
/Chapter 16 · Summary Reports & Pivots
Lesson 16.5·garden_shop
Lesson 16.5

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 dimensionsindependently: 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".

Pattern
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 row there is no single category, so category_name comes back as NULL. Wrap each dimension in coalesce() to give those subtotal rows a readable label like "All categories".

Schema · Garden ShopTable · products9 columns · 24 rows
Table · products

One row per product, with price, cost, and inventory levels.

9 columns · 24 rows
product_id intproduct_name textcategory_id intsupplier_id intprice decimalcost decimalquantity_on_hand intreorder_level intdiscontinued bool
Your task

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.

SQL Workbench
query.sqlgarden_shop · SQL engine loading
⌘↵ to run
·
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.