HAVING: WHERE for groups
WHERE filters rows before they're grouped. To filter the groups themselves, by their count or
total, use HAVING, which comes after GROUP BY:
SELECT subcategory, COUNT(*) AS products
FROM products
GROUP BY subcategory
HAVING COUNT(*) >= 5This keeps only the subcategories with five or more products.
HAVING usually repeats the aggregate (COUNT(*)) rather than the alias (products): that works
in every database.
Other databases: DuckDB, MySQL and BigQuery also accept the alias in
HAVING(HAVING products >= 5). PostgreSQL and SQL Server don't, so repeating the aggregate is the safe habit.