GROUP BY example
We count how many customers there are in each city:
SELECT city, COUNT(*) AS customers
FROM customers
GROUP BY city
ORDER BY customers DESC, city ASC;The twelve original rows become six groups. The sort does not form the groups: it just shows the cities with the most customers first.
Check the result with small data
Three customers are spread across two cities.
WITH customers(name, city) AS (
VALUES ('Amy','London'), ('Liam','London'), ('Eva','Leeds')
)
SELECT city, COUNT(*) AS people
FROM customers GROUP BY city ORDER BY city;| city | people |
|---|---|
| Leeds | 1 |
| London | 2 |
GROUP BY forms one group per city; COUNT(*) counts the rows in each group. One output row per city does not mean there is only one customer.
Check your understanding: What would happen if you added another person from Leeds?
Show answer
Leeds would have 2 people and there would still be two groups. The number of rows depends on how many different cities there are, not on how many people.
How GROUP BY is used
Every selected column must have a clear role: either it identifies the group or it holds an aggregate calculation. Ask yourself “what does one final row represent?”. In a summary by city, a row represents a city, not a customer.
WHERE filters rows before forming the groups. HAVING filters groups after they are calculated. That difference decides where each condition belongs.
Common mix-ups with GROUP BY
Selecting a column that does not identify the group
SELECT city, name, COUNT(*) ... GROUP BY city does not say which name to show for a city with several people. Some engines reject the query and others may return an arbitrary value. Select only the grouping keys and the aggregates.
The grouping level also defines the shape of a report. In the guide on PIVOT with SUM and CASE you group by region only, so that the channels become columns, and then check the resulting grid.