The HAVING clause filters groups created using GROUP BY.  The HAVING clause determines whether a group is included within the result.   

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
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.  

Additional Resources 

To learn more about HAVING, check out these useful resources: 

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>