π SQL GROUPING SETS β Advanced Grouping for Custom Summaries
The SQL
GROUPING SETSclause 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 multipleGROUP BYqueries.
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 BYqueries combined withUNION 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:
| region | year | amount |
|---|---|---|
| East | 2023 | 500 |
| East | 2024 | 700 |
| West | 2023 | 600 |
SELECT region, year, SUM(amount) AS total_sales
FROM sales
GROUP BY GROUPING SETS (
(region, year),
(region),
(year),
()
);
π§Ύ Result:
| region | year | total_sales |
|---|---|---|
| East | 2023 | 500 |
| East | 2024 | 700 |
| West | 2023 | 600 |
| East | NULL | 1200 |
| West | NULL | 600 |
| NULL | 2023 | 1100 |
| NULL | 2024 | 700 |
| NULL | NULL | 1800 |
π― 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
| Feature | GROUPING SETS | ROLLUP | CUBE |
|---|---|---|---|
| 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 SETSallows you to define custom groupings in one query- Itβs more flexible than
ROLLUPorCUBE - Reduces the need for
UNION ALLacross multiple queries - Ideal for reporting and data aggregation tasks