sqladvanced
GROUPING SETS, CUBE, and ROLLUP
Generate multiple levels of aggregation in a single query with grouping sets.
sqlPress ⌘/Ctrl + Shift + C to copy
-- 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.
sqlbeginner
Aggregate Strings with STRING_AGG / GROUP_CONCAT
Concatenate values from multiple rows into a single string per group.
Best for: Comma-separated lists in reports
#sql#string-agg
sqlintermediate
Conditional Aggregation with FILTER / CASE
Compute multiple conditional aggregates in a single query using FILTER or CASE.
Best for: Pivot-style reports
#sql#conditional
sqlintermediate
JSON Aggregation and Querying
Aggregate related rows into JSON arrays and query JSONB columns with PostgreSQL native JSON operators.
Best for: API response building
#json#jsonb
sqlbeginner
String Aggregation with GROUP BY
Concatenate grouped values into comma-separated strings using STRING_AGG with ordering and filtering.
Best for: Tag lists per item
#aggregation#string-agg