Title - HAVING SQL statement Tags - sql statement aggregrate
You can filter which groups to include and exclude in a GROUP BY query.
For example, you may want to see how many movies of different genres are produced each year - but you only care about years and genres with at least 10 movies.
HAVING is similar to WHERE, but allows you to filter groups rather than rows.
Despite the difference, all WHERE statements can also be used with HAVING.
HAVING always comes:
- After GROUP BY
- Before ORDER BY and LIMIT
Example:
This -
SELECT price, ROUND(AVG(downloads)), COUNT(*) FROM fake_apps GROUP BY price;
Will return -
Average downloads (rounded) - and the number of apps - at each price point.
But some apps don’t have many apps so their average downloads are less meaningful.
The following would restrict the query to price points that have more than 10 apps.