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

Fundamental Difference: Filter Timing

WHERE filters rows before grouping; HAVING filters groups after aggregation—understanding execution order.

Fundamental Difference: Filter Timing

You'll learn: How WHERE and HAVING differ based on when they filter data during query execution.

When Filters Actually Run

The key to understanding WHERE vs HAVING is knowing that SQL queries execute in a specific order, not the order you write them. This timing determines what data each clause can access:

WHERE filters before grouping happens. It examines individual rows in your table and decides which ones to include before any aggregation occurs. WHERE cannot see aggregate functions like SUM() or COUNT() because those haven't been calculated yet.

HAVING filters after grouping and aggregation. It examines the summarized groups that GROUP BY created and decides which groups to include in the final result. HAVING can use aggregate functions because they've already been computed.

The Execution Order That Matters

Think of it like a factory assembly line:

  1. FROM – Get the raw materials (table data)
  2. WHERE – Inspect and reject defective parts (filter individual rows)
  3. GROUP BY – Sort parts into bins (create groups)
  4. Aggregate Functions – Count or measure each bin
  5. HAVING – Inspect and reject bins that don't meet standards (filter groups)
  6. SELECT – Package the results
  7. ORDER BY – Arrange packages for delivery

WHERE happens at step 2, before grouping. HAVING happens at step 5, after aggregation. This explains why WHERE total_sales > 1000 fails (total_sales doesn't exist yet at step 2), but HAVING SUM(sales) > 1000 works perfectly (the sum exists at step 5).

Key Takeaway: WHERE filters individual rows before grouping; HAVING filters aggregated groups after grouping—choose based on what you're filtering and when that data becomes available in the query execution order.