[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 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:

SELECT COUNT(*), department
FROM employees
WHERE COUNT(*) > 5  -- This won't work!
GROUP BY department;

This fails because COUNT(*) is only computed after the rows are grouped, and WHERE operates before grouping.

HAVING

The HAVING 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

Example:

SELECT COUNT(*), department
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;  -- This works!


Comments