Aggregation and Grouping · Problem 27 of 118

Customers per Country

EasyAggregation and GroupingShop data

Return each country and the number of customers living there, as customers. Show the biggest country first; sort ties by country.

Hint 1

GROUP BY country makes one row per country; COUNT(*) counts the rows in each group.

Reference solution

SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC, country;

GROUP BY splits the rows into groups with the same value, and each aggregate function (COUNT, SUM, AVG, MIN, MAX) is calculated once per group. Every column in the SELECT list must either be in the GROUP BY or be inside an aggregate function. SQLite is lenient and lets the wrong version run (it returns one arbitrary country), which is exactly why you must check your results.