sqladvanced

GROUPING SETS, CUBE, and ROLLUP

Generate multiple levels of aggregation in a single query with grouping sets.

sql
-- ROLLUP: hierarchical subtotals
SELECT
  region,
  product_category,
  SUM(revenue) AS total_revenue
FROM sales
GROUP BY ROLLUP(region, product_category)
ORDER BY region NULLS LAST, product_category NULLS LAST;

-- CUBE: all dimension combinations
SELECT
  year, quarter, region,
  SUM(sales) AS total
FROM quarterly_sales
GROUP BY CUBE(year, quarter, region);

-- GROUPING SETS: specific combinations
SELECT
  COALESCE(region, 'ALL') AS region,
  COALESCE(category, 'ALL') AS category,
  SUM(amount)
FROM orders
GROUP BY GROUPING SETS (
  (region, category),
  (region),
  (category),
  ()
);

Use Cases

  • Report subtotals
  • Pivot-style aggregations
  • Data warehouse queries

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.