SQL ยท Chapter 22 of 42
SQL HAVING
HAVING filters GROUPED rows (i.e. after aggregation). WHERE filters raw rows BEFORE grouping.
Rule: WHERE for row-level filters, HAVING for group-level filters.
WHERE vs HAVING
`WHERE age > 18 GROUP BY country HAVING COUNT(*) > 10` first removes minors, then groups, then keeps countries with >10 adult users.
Example 1 (sql)
SELECT country, COUNT(*) AS users
FROM users
GROUP BY country
HAVING COUNT(*) > 10;Output
only countries with >10 usersFilter groups by aggregate.
Example 2 (sql)
SELECT category, AVG(price) AS avg_p
FROM products
WHERE price > 0
GROUP BY category
HAVING AVG(price) > 500;Output
categories with avg price over 500WHERE + HAVING together.
Key points
- HAVING runs AFTER aggregation.
- WHERE runs BEFORE aggregation.
- Use HAVING for `COUNT(*) > n` style filters.
- You can reference aggregates in HAVING.
๐ก Note: If your HAVING clause has no aggregate, it should probably be a WHERE clause instead.
