Concept · Grouping and calculating

GROUP BY with multiple columns

GROUP BY with several columns creates one group for each distinct combination of their values.

Before continuing: This entry is part of the GROUP BY guide. If you are new to the topic, start with GROUP BY.

GROUP BY with several columns: example

The customers table holds several cities and an active column with values 1 and 0. We want to know how many customers there are for each combination.

Verified SQL
SELECT city,
       active,
       COUNT(*) AS customers
FROM customers
GROUP BY city, active
ORDER BY city, active DESC;

London appears twice because there are two combinations: ('London', 1) and ('London', 0). If we grouped only by city, both would fall into a single group of four customers.

How GROUP BY with several columns is used

The non-aggregated columns you show in SELECT must identify the group unambiguously. For a portable approach that is easy to reason about, include in GROUP BY every non-aggregated column in the result.

What changes from case to case

What each summary row represents
Grouped byEach result row represents…
GROUP BY citya city
GROUP BY city, activea combination of city and active flag
GROUP BY customer_id, statusa combination of customer and order status

The key question is still the same: “what does a row represent after grouping?”. Adding columns to GROUP BY makes that unit of analysis more specific.

Common mix-ups with GROUP BY on several columns

Grouping by only part of what you display

Problem version
SELECT city, active, COUNT(*)
FROM customers
GROUP BY city;

For a portable query, active should not be left ungrouped: a city can contain both active and inactive customers. If you need both dimensions in the result, group by both.

Mistaking grouping for display order

GROUP BY city, active does not guarantee the result comes back in that order. If presentation matters, add an explicit ORDER BY clause.

Adding columns without checking the granularity

Every extra column can split existing groups into smaller ones. If you add a nearly unique key, you can end up with one-row groups and lose the summary you were after.