Revisiting GROUP BY ROLLUP with a more realistic example


Ever had a random piece of knowledge from school suddenly click in a real-world scenario?
It felt like that for me remembering about ROLLUP a few days ago.
I wrote about GROUP BY ROLLUP roughly 1.5 years agoโone of my first posts here. At the time, it was unfamiliar to me, and I had no idea Iโd ever need it. But this week, I finally encountered a real use case.
๐๐ก๐ ๐๐ซ๐จ๐๐ฅ๐๐ฆ
Imagine we have sales data for a retail store, where each product belongs to a subcategory and a category (e.g., Apples โ Fruits โ Food).
We want to compute the average ordered quantity per product, but with a hierarchical fallback:
- If thereโs no product-level data, use the subcategory average.
- If thatโs missing, use the category average.
- If still unavailable, fall back to the overall average across all products.
๐๐จ๐ฐ ๐๐๐๐๐๐ ๐๐๐ฅ๐ฉ๐ฌ
When we GROUP BY ROLLUP (category, subcategory, product_id), we get multiple aggregation levels in one query:
โ
Per product
โ
Per subcategory
โ
Per category
โ
Across all rows
This allows us to build a lookup table, which we can use with multiple LEFT JOINs to apply the fallback logic.
๐๐๐ญ'๐ฌ ๐ญ๐๐ฌ๐ญ ๐ข๐ญ
Hereโs how it works in practice:
โข Apples โ Direct sales data โ AVG(quantity) = 6
โข Mangoes โ No past sales โ Uses Fruits subcategory โ AVG(quantity) = 4.67
โข Cucumbers โ No past sales, no Vegetables subcategory data โ Uses Food category โ AVG(quantity) = 4.67
โข Washing Machine โ No sales data, no relevant category โ Uses overall average โ AVG(quantity) = 6
๐๐ง ๐ฅ๐ข๐๐ฎ ๐จ๐ ๐ ๐๐จ๐ง๐๐ฅ๐ฎ๐ฌ๐ข๐จ๐ง
This was a fun experiment, but letโs be honestโthis could also be done with window functions!
Still, ROLLUP provides an perspective, and Iโm on the lookout for an even better use case.
Have you ever had an SQL feature suddenly โclickโ for you?
Found it useful? Subscribe to my Analytics newsletter at notjustsql.com.
Subscribe to my newsletter
Read articles from Constantin Lungu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Constantin Lungu
Constantin Lungu
Senior Data Engineer โข Contractor / Freelancer โข GCP & AWS Certified