The HAVING Clause
In its most common use, the HAVING clause is a WHERE clause for groups. Just as WHERE limits rows, HAVING limits groups. Most of the time, you use HAVING with GROUP BY.
SELECT select_list
FROM table_list
[WHERE conditions]
[GROUP BY group_by_list]
[HAVING conditions]
[ORDER BY order_by_list]
When there are aggregates in the SELECT list of a query, WHERE clause conditions apply to the rows that are used to calculate the aggregates, while HAVING conditions apply to the final results after you've calculated the aggregates and set up the groups. One way to keep this difference in mind is to recall the order of the clauses in the SELECT statement. Remember that WHERE comes after FROM, and HAVING comes after GROUP BY. An example ...
Get Practical SQL Handbook, The: Using SQL Variants, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.