Introduction to GROUP BY
What you'll learn: How to use GROUP BY to split your data into meaningful subsets so you can calculate statistics separately for each group.
The Core Idea
Imagine you have a sales table with thousands of transactions from different regions. You want to know the total sales per region, not just overall sales. That's where GROUP BY comes in.
Without GROUP BY, aggregate functions like SUM() or AVG() collapse your entire dataset into a single number. GROUP BY changes the game: it partitions your data into separate groups based on one or more columns, then performs the aggregate calculation independently for each group.
Think of it like sorting laundry: you separate clothes into piles (whites, colors, delicates), then handle each pile differently. GROUP BY creates those piles based on column values.
When to Use GROUP BY
Use GROUP BY whenever you want to answer questions like:
- "What are the total sales by region?"
- "How many customers per product category?"
- "What's the average order value for each month?"
The pattern: you want a summary statistic broken down by some category or dimension.
Basic Syntax Pattern
SELECT category_column, AGGREGATE_FUNCTION(value_column)
FROM table_name
GROUP BY category_column;
The column(s) in GROUP BY must match the non-aggregated columns in your SELECT list. You're essentially saying: "Create a group for each unique value in this column, then calculate aggregates within those groups."
Key Takeaway: GROUP BY transforms aggregate functions from calculating one value for the entire dataset to calculating separate values for each distinct group defined by your grouping column(s).