The GROUP BY mental model
SUM(price) WHERE customer = 'Ana' gave one customer's total. What about every customer's total, in one query? That is GROUP BY:
SELECT customer, COUNT(*), SUM(price) FROM orders GROUP BY customer ORDER BY customer;
Picture it in three steps:
- Sort rows into buckets. Every row with the same
customervalue lands in the same bucket. - Aggregate each bucket separately. COUNT and SUM run once per bucket, not once overall.
- Output one row per bucket.
So the query returns one line per customer: their name, their number of orders, their total spend.
Code exercise · sql
Run it. One output row per customer: name, order count, total spent. Compare with the figure.
Quiz
In `SELECT customer, SUM(price) FROM orders GROUP BY customer;`, what does SUM(price) add up?
Code exercise · sql
Your turn. Count how many times each ITEM was ordered. One row per item, alphabetical order.
Code exercise · sql
Drill. What is the average price of each item? One row per item, alphabetical, with the average rounded to 2 decimals. (Each item here always costs the same, so the averages look plain, but the query shape is the everyday one.)