Time to learn GROUP BY! This powerful SQL feature lets you break down your data into groups and calculate totals for each group separately.
Instead of one grand total, you get totals per category, per customer, or per month.
Engagement Message
Can you give me one example where per-category totals are more useful than a single grand total?
GROUP BY works by collecting rows with the same values into groups. Then aggregate functions like COUNT and SUM calculate results for each group individually.
Think of it like sorting your data into piles, then counting each pile separately.
Engagement Message
If you GROUP BY customer_id, what would each group contain?
The functionality is most clearly explained by using a comparison. First, let's revisit how aggregation works without GROUP BY, as mentioned in the previous units.
Given this ORDERS table:
If you want the grand total of all order amounts, you can use:
Result:
This gives you just one number: the total for all orders combined.
Engagement Message
Do you recognize this?
Now let's see what happens when you add GROUP BY.
To get the total order amount for each customer, use:
Result:
