sql-where-vs-having--t3chat--1(1).jpg

📌 TL;DR

It's strictly about timing of execution:

<aside> 💡

If you need to filter by a calculated value (like SUM or COUNT), you need HAVING.

</aside>


The Execution Flow

To understand the difference, we have to look at how the database engine actually processes the query. It doesn't read top-to-bottom; it follows a specific order of operations:

  1. FROM (Find the table)
  2. WHERE (Filter raw rows - "Pre-filter")
  3. GROUP BY (Bucket the remaining rows)
  4. HAVING (Filter the buckets - "Post-filter")
  5. SELECT (Return the columns)

1. GROUP BY

Before you can filter groups, you have to make them. GROUP BY collapses multiple rows into a single row based on shared values.

<aside> 💡

Once you group, you lose access to individual row details unless you wrap them in an aggregate function (SUM, AVG, MAX, ARRAY_AGG).

</aside>

Practical examples