Conditions with the results of group functions can be specified only in the HAVING part:
SELECT cities.name, COUNT(users.cities_id) FROM cities LEFT JOIN users ON users.cities_id = cities.id GROUP BY cities.name HAVING COUNT(users.cities_id) > 3
To understand the logic of the SQL query, it is customary to represent the order in which its parts are executed as follows (in reality, for the purposes of optimization, the DBMS is done a little differently):
- from
- ON in join
- where
- group by
- having
- select
- order by
- offset, limit
All aggregate functions are calculated during phase 4, when a group by of primary lines collects total. During the execution of the where phase, which is designed to work with the primary rows of tables, groups, and the results of the calculation of group functions are not yet, therefore aggregate functions cannot be used in this phrase. The phrase having is used to filter the final lines generated during the grouping.
PS In principle, if having not been (and in some other cases) the same effect can be obtained as follows:
SELECT * FROM ( SELECT cities.name, COUNT(users.cities_id) as CNT FROM cities LEFT JOIN users ON users.cities_id = cities.id GROUP BY cities.name ) X WHERE CNT > 3