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:

  1. If thereโ€™s no product-level data, use the subcategory average.
  2. If thatโ€™s missing, use the category average.
  3. 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.

0
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