What is the difference between WHERE and HAVING, and why can't you use an aggregate function like SUM() in a WHERE clause?
Last updated
WHERE filters individual rows before grouping and aggregation, while HAVING filters groups after aggregation. You can't use an aggregate like SUM() in WHERE because the aggregate doesn't exist yet at the point WHERE runs.
WHERE:Applied row-by-row before
GROUP BY; can only reference raw column values, not aggregates.Reduces rows early, so it's cheaper and can use indexes.
HAVING: Applied after grouping; can reference aggregate results (e.g.HAVING SUM(amount) > 1000).Why no aggregate in WHERE: Logical order of evaluation is
FROMthenWHEREthenGROUP BYthenHAVING; aggregates are computed at the grouping step, afterWHEREhas already finished.Best practice: filter with
WHEREwhenever possible and reserveHAVINGfor conditions on aggregates.
[lang:sql]
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'paid' -- filters rows first
GROUP BY customer_id
HAVING SUM(amount) > 1000; -- filters groups after
- https://www.postgresql.org/docs/current/tutorial-agg.html
- https://www.freecodecamp.org/news/a-beginners-guide-to-sql/
- https://www.freecodecamp.org/news/sql-group-by-clauses-explained/
- https://dev.to/neha_christina_1ac8651819/group-by-aggregate-functions-explained-the-where-vs-having-mistake-almost-everyone-makes-1nfg
- https://dev.to/t/sql
- https://dev.to/solo_495/where-vs-having-in-sql-a-simple-way-to-understand-the-difference-2ihp
- https://dev.to/somadevtoo/difference-between-where-vs-having-clause-in-sql-17g5
- https://medium.com/@mariakangan/why-you-cant-use-aggregate-functions-in-where-and-when-to-use-having-instead-a702cc33894c