The WHERE
clause filters data from the source before aggregates, whereas HAVING
clause filters data after the GROUP BY
has been applied. Generally this means any non-aggregate filter can appear in either place, but if you have a column that is not referenced in your query, you can only filter it in a WHERE
clause.
For example, if you have the following table:
| ID | VALUE |
--------------
| 1 | 15 |
| 2 | 15 |
| 3 | 20 |
| 4 | 20 |
| 5 | 25 |
| 6 | 30 |
| 7 | 40 |
Suppose you wanted to apply the following query:
select value, count(value)
from Table1
group by value
But you only wanted to include rows where ID > 2
. If you put that in a HAVING
clause, you will get an error, because the ID
column is not available post aggregate as it is not in the SELECT
clause. In that case, you would be required to use a WHERE
clause instead:
select value, count(value)
from Table1
where id > 2
group by value