All SQL topics
SQL TOPIC

SQL GROUP BY practice: totals per group

GROUP BY splits rows into groups and runs the aggregate once per group: revenue per country, orders per month.

Every selected column must either be in the GROUP BY or inside an aggregate. SELECT country, COUNT(*) … GROUP BY country gives one row per country.

Group by more than one column for finer breakdowns, such as country and segment.

Worked example

How many customers are in each country?

SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC, country;
Result on the sample data
countrycustomers
Germany4
France3
Greece3
Ireland3
Netherlands3
Italy2
Spain2

Common mistakes

  • Selecting a column that is neither grouped nor aggregated.
  • Grouping by an ID when you meant a name, which splits one group into many.