How does SQL GROUP BY work when grouping across multiple columns? | A1Lab@HumairaM to SQLEnglish • 2 days ago

How does SQL GROUP BY work when grouping across multiple columns?

message-square
0

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:

  1. ('North', 'Card') -> rows 1 and 2 (SUM = 300, COUNT = 2)
  2. ('North', 'Cash') -> row 3 (SUM = 150, COUNT = 1)
  3. ('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_method sets the output grain (one row per unique region + payment_method pair).
  • Add an explicit ORDER BY when display order matters; GROUP BY does 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, b and GROUP BY b, a produce 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 WHERE to filter individual rows before grouping, and HAVING to 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

  1. Include all non-aggregated SELECT columns in GROUP BY: Otherwise SQL engines (including SQL Server, PostgreSQL, and MySQL with ONLY_FULL_GROUP_BY) raise an error.
  2. Use WHERE for pre-aggregation row filters and HAVING for post-aggregation group filters.
  3. Add ORDER BY explicitly whenever sorted results are required.