GROUP BY Execution Order
What you'll learn: You'll understand the precise order SQL processes your query components, especially how WHERE filters before GROUP BY aggregates.
The Mental Model
When you write a SQL query with filtering and grouping, it doesn't execute in the order you write it—SQL has its own internal logic. Think of it like a restaurant kitchen: the chef doesn't necessarily cook dishes in the order they appear on the menu. SQL follows a specific execution sequence to efficiently process your request.
The Execution Order
Here's what actually happens inside SQL when you combine WHERE and GROUP BY:
- FROM: SQL identifies which table(s) to use
- WHERE: Filters individual rows before any grouping happens
- GROUP BY: Groups the filtered rows into categories
- SELECT: Applies aggregate functions to each group and projects columns
- ORDER BY: Sorts the final result
Why This Matters
Understanding execution order prevents common mistakes. For example:
SELECT category, COUNT(*) as total
FROM products
WHERE price > 50
GROUP BY category
ORDER BY total DESC
What happens step-by-step:
- WHERE eliminates all products under $50 first
- GROUP BY then groups only the remaining expensive products by category
- SELECT counts how many products are in each group
- ORDER BY sorts categories by their counts
You cannot reference aggregate results in the WHERE clause because aggregates don't exist yet at that stage! WHERE sees only individual rows, not grouped summaries.
Common Pitfall
This won't work: WHERE COUNT(*) > 5 because WHERE executes before grouping. The aggregation hasn't happened yet, so there's nothing to count.
Key Takeaway: SQL executes queries in a fixed order: WHERE filters raw rows first, GROUP BY aggregates those filtered rows second, then SELECT projects the results. Understanding this order helps you write correct queries and debug errors.