The real difference between WHERE and HAVING
WHERE filters source rows; HAVING filters groups after aggregation.
Problem and reasoning
WHERE decides which detail rows participate before GROUP BY, while HAVING decides which groups remain after grouping and aggregation. Raw date, status, and region predicates normally belong in WHERE; aggregate order-count or sales-total predicates belong in HAVING.
Putting row predicates in HAVING may depend on permissive database behavior and obscures intent. Filter early with WHERE when possible, which can also reduce the amount of data entering aggregation.
For debugging, establish correct detail rows with WHERE, add GROUP BY, and then add HAVING while checking row or group counts at every step.
Examples
Sample table
orders| department | amount |
|---|---|
| Sales | 1200 |
| IT | 900 |
| Sales | 1500 |
| HR | 700 |
Before / Not recommended
SELECT department, SUM(amount) AS total FROM orders GROUP BY department HAVING department = 'Sales';Before result
| department | total |
|---|---|
| Sales | 2700 |
After / Recommended
SELECT department, SUM(amount) AS total FROM orders WHERE department = 'Sales' GROUP BY department;After result
| department | total |
|---|---|
| Sales | 2700 |
Why it is better:The result is the same, but WHERE expresses the row predicate before aggregation; reserve HAVING for post-group conditions such as SUM or COUNT.
Was this explanation clear?
Thanks. This feedback will inform the next content review.