GROUP BY Multiple Columns
Group by both category and status to see order counts for every product-category/status combination.
Overview
You can GROUP BY more than one column to get finer-grained buckets. The query
produces one row per combination of the grouped values. Here we group store
orders by product category and order status to see how many orders of each
type landed in each state.
The Query
Store (Customers/Orders/Products)
Loading database engine...
Step-by-Step Breakdown
GROUP BY p.category, o.status— buckets are defined by the pair(category, status).COUNT(*)counts orders in each bucket;SUM(o.quantity)totals units sold in that bucket.- The result has one row per distinct category/status pair that exists.
Order of grouped columns
The order you list columns in GROUP BY doesn't change the buckets, but it
does affect the default sort if you don't add an explicit ORDER BY.
Variations
Group by customer city and active status:
Store (Customers/Orders/Products)
Loading database engine...
Common Mistakes
- Selecting a column you didn't group or aggregate. Every non-aggregated
SELECTcolumn must appear inGROUP BY. - Too many groups. Adding a high-cardinality column (like an
id) toGROUP BYcollapses the aggregation back to near one-row-per-input. - Confusing
WHEREandHAVING. Filter rows before grouping withWHERE; filter groups after withHAVING.