GROUPING SETS Explained
Pick exactly the groupings you want.
What Are GROUPING SETS?
When you write a GROUP BY clause, you define one set of columns to group by. But sometimes you need multiple different groupings in a single query — without running the query several times and using UNION ALL.
GROUPING SETS lets you specify exactly which groupings you want, all in one pass over the data. Each set in the list produces its own aggregated rows in the result.
Sample Table: sales
We will use a sales table throughout this lesson. It records transactions by region, product category, and amount.
Run the code to create and populate the table so you can follow along with every example.
CREATE TABLE sales (
region TEXT,
category TEXT,
amount NUMERIC
);
INSERT INTO sales VALUES
('East', 'Electronics', 500),
('East', 'Clothing', 200),
('West', 'Electronics', 300),
('West', 'Clothing', 400),
('North', 'Electronics', 150),
('North', 'Clothing', 250);All lessons in this course
- Beyond a Single GROUP BY
- ROLLUP for Subtotals
- CUBE for All Combinations
- GROUPING SETS Explained