Loading…
You've learned that WHERE filters individual rows. But what if you want to filter groups after using GROUP BY? That's where HAVING comes in!
| Clause | Filters... | When it runs |
|---|---|---|
| <code>WHERE</code> | Individual rows | Before grouping |
| <code>HAVING</code> | Groups | After grouping |
-- This DOESN'T work:
SELECT category, COUNT(*) FROM products
WHERE COUNT(*) > 1 -- ❌ ERROR! Can't use aggregate in WHERE
GROUP BY category;-- This DOES work:
SELECT category, COUNT(*) FROM products
GROUP BY category
HAVING COUNT(*) > 1; -- ✅ Filters after grouping
FROM products — start with all rowsGROUP BY category — create groups (Electronics: 2, Office: 2, Books: 1)HAVING COUNT(*) > 1 — remove groups with 1 or fewer itemsDon't use WHERE for aggregate conditions — always use HAVING.
Find categories that have more than 1 product. Show the category and the count.
Downloading SQL engine… (one-time)
This runs entirely in your browser and is cached for next time.