Advanced SQL Topics
HAVING
The HAVING keyword can make your life easier when dealing with GROUP BY statements — imagine we’d like to see each state’s Average 2022 population estimate, but we’d also only like to see states with a total of 7 million people in their cities represented in the top 23.
SELECT ST, AVG(2022 estimate)
FROM database_table
GROUP BY ST
HAVING SUM(2022 estimate) >= 7,000,000
If the HAVING statement was not there, it would be difficult to ensure that we’re filtering for States with a total population of at least 7 million.
Imagine we wanted to filter for states with at least two entries in the top 23. We’d add “ HAVING COUNT(ST) >= 2 “ to calculate that faster.
You can also use any other aggregations with a HAVING statement