[MySQL] `WHERE` vs `HAVING`
WHERE vs HAVING
How did I encounter this?
I got an error when sending a query to game_db. It was about row aggregation was not correct. I realized that aggregating within WHERE was the cause. I was supposed to do that using HAVING outside WHERE.
Understanding the difference between WHERE and HAVING
WHERE
The
At this point, aggregate functions (like
WHERE clause is applied before GROUP BY. It works on individual rows from the table.At this point, aggregate functions (like
COUNT(), SUM(), AVG()) haven’t been calculated yet, because grouping hasn’t occurred. This acts likes a filter at the start against each row. Example:
This fails because COUNT(*) is only computed after the rows are grouped, and WHERE operates before grouping.
HAVING
TheHAVING clause is applied after GROUP BY and works on aggregated data. Aggregate functions like COUNT(), SUM(), or AVG() are valid here because they are already computed at this stage. This acts like a filter at the end against grouped rows
Comments
Post a Comment