WHERE vs HAVING: what is the difference?
Understand the concept
WHERE filters individual rows before groups are built, while HAVING filters the groups produced by aggregation. They exist at different logical stages of a query. Use WHERE for conditions on source rows and HAVING for conditions such as “the group's total is greater than 1000.”
Important ideas
-
WHEREfilters rows before grouping. -
HAVINGfilters groups after aggregation. -
Example: filter paid orders with WHERE, then customers spending over 1000 with HAVING.
-
A condition on an aggregate such as
SUM(amount)generally belongs in HAVING, not WHERE.
Work through the example
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(amount) > 1000;- Only paid orders enter the groups; only customer groups over 1000 remain.
Can you explain it without the notes?
WHERE vs HAVING: what is the difference?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
WHERE filters individual rows before groups are built, while HAVING filters the groups produced by aggregation. They exist at different logical stages of a query. Use WHERE for conditions on source rows and HAVING for conditions such as “the group's total is greater than 1000.”
Turn this concept into a clear answer.
- Explain the rows that enter the group separately from the groups that survive the final filter.
Adapted from 05_SQL_POSTGRESQL.md · “WHERE vs HAVING: what is the difference?”. Examples are study fragments; framework behavior can depend on your version.