When you group across multiple columns in SQL (GROUP BY col1, col2, ...), SQL creates one group for each unique combination of values across all listed columns—not separate groups per column. Aggregate functions (COUNT, SUM, AVG, MIN, MAX) are then computed separately for each unique combination, and every non-aggregated column in SELECT must either appear in GROUP BY or be inside an aggregate function.
1. How Unique Combinations Work
Suppose a sales table has these rows:
region |
payment_method |
amount |
|---|---|---|
North |
Card |
100 |
North |
Card |
200 |
North |
Cash |
150 |
South |
Card |
300 |
Grouping by region, payment_method produces 3 unique groups:
('North', 'Card')-> rows 1 and 2 (SUM = 300,COUNT = 2)('North', 'Cash')-> row 3 (SUM = 150,COUNT = 1)('South', 'Card')-> row 4 (SUM = 300,COUNT = 1)
Rows with ('North', 'Card') and ('North', 'Cash') remain distinct groups even though both share region = 'North'.
2. Multi-Column GROUP BY Example
SELECT
region,
payment_method,
COUNT(*) AS transaction_count,
SUM(amount) AS total_amount,
AVG(amount) AS avg_amount
FROM sales
GROUP BY
region,
payment_method
ORDER BY
region ASC,
total_amount DESC;
GROUP BY region, payment_methodsets the output grain (one row per uniqueregion+payment_methodpair).- Add an explicit
ORDER BYwhen display order matters;GROUP BYdoes not guarantee sort order.
3. NULL Behavior in Multi-Column Grouping
Unlike = comparisons where NULL = NULL is unknown, GROUP BY treats all NULL values in a grouping column as one shared group:
- Rows with
(region = 'North', payment_method = NULL)and(region = 'North', payment_method = NULL)group together. (region = 'North', payment_method = NULL)stays separate from(region = 'North', payment_method = 'Card').
4. Column Order, Granularity, and HAVING vs. WHERE
GROUP BY a, bandGROUP BY b, aproduce the same unique(a, b)combinations and aggregate values, though output column order and execution plans can differ.- Adding columns makes each row more granular (more rows, smaller groups); removing columns makes each row more summarized (fewer rows, larger groups).
- Use
WHEREto filter individual rows before grouping, andHAVINGto filter groups after aggregation:
SELECT
region,
payment_method,
COUNT(*) AS transaction_count,
SUM(amount) AS total_amount
FROM sales
WHERE status = 'COMPLETED'
GROUP BY
region,
payment_method
HAVING SUM(amount) >= 250
ORDER BY
total_amount DESC;
Key Rules to Avoid Errors
- Include all non-aggregated
SELECTcolumns inGROUP BY: Otherwise SQL engines (including SQL Server, PostgreSQL, and MySQL withONLY_FULL_GROUP_BY) raise an error. - Use
WHEREfor pre-aggregation row filters andHAVINGfor post-aggregation group filters. - Add
ORDER BYexplicitly whenever sorted results are required.
You must log in or register to comment.
