WHERE versus HAVING
Before and after grouping.
Where and having both filter. So how do you choose? It's all about timing. One runs before the piles are made, and the other runs after.

- Both of them filter
- It's about timing
- Before, or after grouping
Before and after
Where runs before grouping. It looks at single rows, like a book's price. Having runs after grouping. It looks at whole groups, like the number of books in a genre. If your test uses count, sum, average, min, or max, it belongs in having. Otherwise, use where.
WHERE
- Before grouping
- Tests single rows
- price > 15
HAVING
- After grouping
- Tests whole groups
- COUNT(*) >= 3
Both in one query
Here's a query with both. First, where keeps only books over fifteen dollars. Then group by makes a pile per genre. Then having keeps genres with at least three of those pricey books. Run it. Five genres have three books over fifteen dollars.
SELECT genre, COUNT(*) AS pricey_books
FROM books
WHERE price > 15
GROUP BY genre
HAVING COUNT(*) >= 3;โโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ genre โ pricey_books โ โโโโโโโโโโโโโโผโโโโโโโโโโโโโโโค โ Business โ 3 โ โ Cooking โ 3 โ โ Fantasy โ 3 โ โ History โ 3 โ โ Technology โ 3 โ โโโโโโโโโโโโโโดโโโโโโโโโโโโโโโ
The order SQL really works in
Here's a secret. SQL doesn't run your query in the order you write it. It starts with from, then where, then group by, then having, then select, then order by, and finally limit. That's why you can't use a column alias in where. When where runs, select hasn't happened yet.
- FROMget rows
- WHEREfilter rows
- GROUP BYmake piles
- HAVINGfilter piles
- SELECTpick columns
- ORDER BYsort

Summary
Where filters rows before grouping, having filters groups after. And SQL runs from, where, group by, having, select, order by. Next, a powerful trick that combines case with sum.
Key takeaways- WHERE: rows, before
- HAVING: groups, after
- FROM first, SELECT later