T
Tech Town
Log InSign Up Free
← Back to Blog

June 17, 2025 · admin

GROUPING SETS

πŸ“Š SQL GROUPING SETS – Advanced Grouping for Custom Summaries

The SQL GROUPING SETS clause gives you full control over how to group your data and create multiple groupings in a single query. It’s a powerful alternative to running multiple GROUP BY queries.

With GROUPING SETS, you can avoid writing UNION ALL statements and streamline your reports and dashboards with flexible aggregations.


πŸ“˜ What is SQL GROUPING SETS?

GROUPING SETS is an extension of the GROUP BY clause that allows you to define multiple groupings in a single SQL query.

πŸ” Why use it?

  • It replaces multiple GROUP BY queries combined with UNION ALL
  • Makes summary reports faster and cleaner
  • Works great for roll-up reports, pivot tables, and multi-level aggregations

🧾 SQL GROUPING SETS Syntax

SELECT column1, column2, aggregate_function(column3)
FROM table_name
GROUP BY GROUPING SETS (
  (column1, column2),
  (column1),
  ()
);
  • (column1, column2) – Group by both columns
  • (column1) – Group by column1 only
  • () – Grand total (no grouping)

βœ… Example: Sales Summary by Region and Year

Suppose you have a sales table:

regionyearamount
East2023500
East2024700
West2023600
SELECT region, year, SUM(amount) AS total_sales
FROM sales
GROUP BY GROUPING SETS (
  (region, year),
  (region),
  (year),
  ()
);

🧾 Result:

regionyeartotal_sales
East2023500
East2024700
West2023600
EastNULL1200
WestNULL600
NULL20231100
NULL2024700
NULLNULL1800

🎯 Use Cases for GROUPING SETS

  • πŸ“Š Create subtotal and grand total reports
  • πŸ“† Summarize by date, region, or product combinations
  • πŸ“¦ Build dashboards with flexible drilldowns
  • πŸ“ˆ Generate multiple levels of aggregation in a single query

πŸ’‘ GROUPING SETS vs ROLLUP vs CUBE

FeatureGROUPING SETSROLLUPCUBE
Custom groupingβœ… Fully customizable❌ Fixed hierarchical grouping❌ All combinations
Subtotalsβœ… Yesβœ… Yesβœ… Yes
Grand totalsβœ… Yesβœ… Yesβœ… Yes
Performanceβœ… Better control⚠️ Might be overkill⚠️ Can be slow on big data

🧠 Pro Tip: Use GROUPING() Function

The GROUPING() function helps you detect whether a NULL value in the result is from actual data or a subtotal.

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

πŸ“ Summary

  • GROUPING SETS allows you to define custom groupings in one query
  • It’s more flexible than ROLLUP or CUBE
  • Reduces the need for UNION ALL across multiple queries
  • Ideal for reporting and data aggregation tasks