The WHERE filters data from the source before aggregates, while HAVING clusters the data after applying GROUP BY . As a rule, this means that any non-aggregate filter can appear anywhere, but if you have a column that your query does not refer to, you can filter it only in WHERE .
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 wanted to include lines where ID > 2 . If you put this in the HAVING , you will get an error because the ID column is not an available post aggregate because it is not in the SELECT . In this case, you will need to use the WHERE instead:
select value, count(value) from Table1 where id > 2 group by value
Demo: http://www.sqlfiddle.com/#!2/f6741/16
mellamokb
source share