# The SQL
When we use an aggregate function in a query, such as
AVG, we can't then filter by the result of that aggregation.
For example, this query:
SELECT poll_id, COUNT(id) AS option_count FROM options GROUP BY poll_id;
It might give us something like this:
If you want to for those rows that have a count of 3 or more, you'd think that this would work:
SELECT poll_id, COUNT(id) AS option_count FROM options GROUP BY poll_id WHERE option_count > 2;
But it does not, because the
WHERE clause is evaluated before the aggregation happens.
Instead, to evaluate on the result of the aggregate function, we must use the
SELECT poll_id, COUNT(id) AS option_count FROM options GROUP BY poll_id HAVING COUNT(id) > 2;
Note that you can't use the column alias in the
HAVING clause. You must use the entire aggregate function.
However, this won't run the aggregate function twice (so it's not a performance problem).
# Wrapping Up
Alright, that's about everything for the
HAVING clause. It can be really handy when you want to filter our grouped rows!