Course contentsShow
← Data Science
Lesson 896 of 2,14523. SQL Aggregation and GroupingFree lesson

GROUP BY Execution Order

Understanding SQL query execution order: WHERE filters first, then GROUP BY aggregates, then SELECT projects.

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:

  1. FROM: SQL identifies which table(s) to use
  2. WHERE: Filters individual rows before any grouping happens
  3. GROUP BY: Groups the filtered rows into categories
  4. SELECT: Applies aggregate functions to each group and projects columns
  5. 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.