Aggregation and Grouping · Problem 31 of 118

Frequent Buyers

MediumAggregation and GroupingShop data

Return customer_id and orders (the number of orders) for every customer who has placed at least 8 orders. Sort by orders from high to low, then customer_id.

Hint 1

WHERE filters rows before grouping. To filter on a group's count, use HAVING.

Reference solution

SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 8
ORDER BY orders DESC, customer_id;

The order of evaluation is: FROM, WHERE (filters rows), GROUP BY (makes groups), HAVING (filters groups), SELECT, ORDER BY. A condition on COUNT(*) can only be checked after the groups exist, so it belongs in HAVING. Put conditions on single rows in WHERE: it removes rows early and is faster.