# The SQL HAVING clause

When we use an aggregate function in a query, such as COUNT, SUM, or 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:

poll_id option_count
1 3
2 2
3 3

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.

# Using HAVING

Instead, to evaluate on the result of the aggregate function, we must use the HAVING clause:

SELECT poll_id, COUNT(id) AS option_count
FROM options
GROUP BY poll_id
HAVING COUNT(id) > 2;

WARNING

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)[1].

# Wrapping Up

Alright, that's about everything for the HAVING clause. It can be really handy when you want to filter our grouped rows!


  1. How to avoid invoking functions twice when using GROUP BY and HAVING? (StackOverflow) (opens new window) ↩ī¸Ž