Single Column Grouping
What you'll learn: How to organize rows into groups based on a single column's values so you can calculate separate aggregates for each group.
The Core Idea
Imagine you have a sales table with transactions from multiple stores. Without grouping, aggregate functions like SUM() or AVG() give you one result across the entire table. But what if you want total sales per store?
That's where GROUP BY with a single column comes in. It divides your data into separate "buckets"—one for each unique value in that column—then calculates aggregates independently for each bucket.
How It Works
When you add GROUP BY column_name to a query with aggregate functions, SQL:
- Identifies all distinct values in that column
- Creates a group for each distinct value
- Calculates the aggregate function separately within each group
- Returns one result row per group
Example structure:
SELECT store_name, SUM(sales_amount)
FROM transactions
GROUP BY store_name;
This query groups all transactions by store_name, then sums the sales for each store separately. You get one row per store with its total.
Key Rules
- Every column in your
SELECTlist must either be in theGROUP BYclause or be wrapped in an aggregate function - The grouping column appears in your results to identify which group each aggregate belongs to
- Groups are created from the actual data—if five distinct stores exist, you get five result rows
Key Takeaway: Single column grouping with GROUP BY transforms your aggregates from table-wide calculations into per-group calculations, letting you analyze patterns and totals for each distinct value in a column.