HAVING vs WHERE
Distinguish HAVING (filters groups) from WHERE (filters rows), and apply both correctly in the same query.
Two Filter Stages
WHERE filters individual rows BEFORE grouping. HAVING filters groups AFTER aggregation. They look similar but operate at different stages.
WHERE Example
WHERE filters raw rows. It cannot see aggregates:
-- Sum totals for rows where status is 'paid':
SELECT user_id, SUM(total) AS revenue
FROM orders
WHERE status = 'paid'
GROUP BY user_id;