In a query that uses GROUP BY, how does the WHERE clause differ from the HAVING clause?
Show the answer and explanation
Correct answer: B, WHERE filters individual rows before grouping, while HAVING filters groups after the aggregates are computed.
Explanation SQL
WHERE filters individual rows before GROUP BY forms groups, so it cannot contain aggregate functions. HAVING filters whole groups after the aggregates are computed, so conditions such as SUM(amount) > 1000 belong there.
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'paid' -- row filter
GROUP BY customer_id
HAVING SUM(amount) > 1000; -- group filterWhy the other statements are wrong:
- Saying WHERE works on groups and HAVING on rows reverses the real order: rows are filtered first, groups afterwards.
- Aggregates are not allowed in WHERE (
WHERE SUM(amount) > 1000is an error), while HAVING may use aggregates and grouped columns. - They are not synonyms: WHERE works on rows and HAVING on groups, so moving a condition between them can change the result or cause an error.
Interview tip: add that row-level conditions belong in WHERE, because filtering early means fewer rows have to be grouped.