Unlike the WHERE clause which filters individual records, the HAVING clause filter groups; however, keep in mind that SQL containing both a WHERE and HAVING processes both!
In this case, the WHERE clause is first processed, and those records filtered. The HAVING is then applied to groups as specified in the GROUP BY.
Typically HAVING is used with GROUP BY, but if a GROUP BY clause isn’t included, then HAVING operates on the entire result set as one implicit group.
Examples using HAVING
In this example, the query returns the employee’s average VacationHours by MaritalStatus and Gender. The HAVING restricts group results from those with average VacationHours greater than 50.
SELECT MaritalStatus, Gender, Avg(VacationHours) AvgVacationHours FROM HumanResources.Employee GROUP BY MaritalStatus, Gender HAVING Avg(VacationHours) > 50
HAVING clause’s key advantage is its ability to filter GROUPS using aggregate functions. This is something you cannot do withing a SELECT statement.
Hint: If you are having a hard time understand HAVING and WHERE’s role within SELECT, I recommend understanding the SELECT statement order of operations first.
To learn more about HAVING, check out these useful resources: