sql tutorial · Intermediate
Summarize data with COUNT, SUM, and AVG, group rows with GROUP BY, and filter groups with HAVING.
Aggregate functions boil many rows down to one value: COUNT, SUM, AVG, MIN, and MAX.
GROUP BY runs the aggregates once per group instead of once for the whole table. Every column in the SELECT must either be in the GROUP BY or inside an aggregate.
WHERE filters rows before they are grouped. HAVING filters the groups afterwards, so it can use aggregates. This finds customers with more than two orders that weren't cancelled.
exercise Show each order's total (quantity × unit price, added up), largest first. Return two columns: order_id and total. Leave out cancelled orders.