softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

SQL GROUPING SETS, ROLLUP, and CUBE – Advanced Aggregations

🔹 Why These Operators Matter

GROUPING SETS, ROLLUP, and CUBE extend GROUP BY to create multiple summary levels within a single query. They are indispensable for dashboards, OLAP-style analysis, and multi-level reporting.

⚙️ GROUPING SETS

SELECT
  region,
  product,
  SUM(amount) AS total_sales
FROM sales
GROUP BY GROUPING SETS (
  (region),
  (product),
  ()
);

Generates custom combinations: totals by region, by product, and the overall grand total in one pass.

⚙️ ROLLUP

SELECT
  region,
  product,
  SUM(amount) AS total_sales
FROM sales
GROUP BY ROLLUP (region, product);

Builds hierarchical subtotals from detailed rows → region totals → overall totals.

⚙️ CUBE

SELECT
  region,
  product,
  SUM(amount) AS total_sales
FROM sales
GROUP BY CUBE (region, product);

Returns every combination of the specified dimensions—perfect for multi-dimensional analytics.

🧠 GROUPING() Helper

SELECT
  region,
  product,
  SUM(amount) AS total_sales,
  GROUPING(region) AS region_flag,
  GROUPING(product) AS product_flag
FROM sales
GROUP BY CUBE (region, product);
📘 GROUPING() returns 1 when the column is aggregated (the NULL comes from a subtotal row).

⚖️ Comparison Snapshot

Feature GROUPING SETS ROLLUP CUBE
PurposeCustom combinationsHierarchical subtotalsAll combinations
Grand totalOptionalAlways includedAlways included
PerformanceLightestModerateHeaviest
Typical useTailored reportsDrill-down summariesOLAP cubes

💡 Practical Use Cases

🧠 Interview Tip

“ROLLUP generates hierarchical totals, CUBE enumerates every combination, and GROUPING SETS lets you hand-pick the summary levels needed for the report.”
← Back to Articles | 🏠 Back to Homepage