WHERE Filters Rows; HAVING Filters Groups
Choose WHERE or HAVING based on whether the condition applies before or after grouping.
Ask one question before choosing the clause: does this condition make sense on one row, or only after several rows have been summarized? Row facts belong in WHERE A row fact can be checked before grouping. Date ranges, statuses, ids, categories, and non-null checks belong here. These filters improve correctness and usually performance because irrelevant rows are removed before aggregation. Summary facts belong in HAVING A summary fact needs aggregate context. COUNT(*) > 500, SUM(revenue) >= 10000, AVG(rating) < 3.5, and COUNT(DISTINCT user_id) >= 50 are group-level checks. They belong after GROUP BY because the values they reference do not…
Sign up free — one personalized lesson every day, matched to your role and goals.
Already have an account? Sign in