How does GROUP BY behave with multiple columns, and what does each combination represent?
GROUP BY on multiple columns creates one group per unique combination of those column values. Each row in the result represents a distinct tuple, and every non-aggregated column in SELECT must appear in the GROUP BY list.
How to think about it
Think of multiple GROUP BY columns as a single composite key: the engine forms one group for each unique combination of the listed values. The more columns you add, the finer the groups split — and that’s the lever the interviewer wants to see you control.
Each row = one unique combination
Group by (country, category, year) and a result row stands for everything matching one tuple — say, all Indian Electronics orders in 2024. If a combination never occurs in the data, there’s simply no row for it; the engine does not zero-fill the missing tuples.
SELECT country, category, order_year,
SUM(revenue) AS total_revenue,
COUNT(*) AS order_count
FROM orders
GROUP BY country, category, order_year
ORDER BY country, category, order_year;
| country | category | order_year | total_revenue | order_count |
|---|---|---|---|---|
| India | Clothing | 2023 | 400 | 1 |
| India | Clothing | 2024 | 200 | 1 |
| India | Electronics | 2024 | 800 | 2 |
| US | Clothing | 2024 | 150 | 1 |
| US | Electronics | 2023 | 600 | 1 |
| US | Electronics | 2024 | 800 | 1 |
Six rows for six distinct tuples. India + Electronics + 2024 is the only combination with two orders, so it’s the only row where order_count is 2 — the two 500 and 300 orders summed to 800. Drop order_year from the GROUP BY and the result coarsens to four rows; the grain follows the key.
The non-aggregated SELECT rule
Every SELECT column that isn’t wrapped in an aggregate must appear in GROUP BY. This isn’t a style preference — it’s enforced by the standard and by PostgreSQL, BigQuery, Snowflake, and SQL Server:
-- ERROR in PostgreSQL/Snowflake/BigQuery:
SELECT country, city, SUM(revenue)
FROM orders
GROUP BY country; -- city is unaggregated but absent from GROUP BY
The engine can’t pick a single city for a group that spans several — so it refuses rather than guess.
Column order doesn’t matter
GROUP BY a, b and GROUP BY b, a form identical groups; the order inside GROUP BY is irrelevant. Only ORDER BY changes how the output is sorted.