Filtering Groups
Learn about filtering groups using HAVING.
Imagine we manage an online store with thousands of products, and we need to identify which product categories have a minimum number of products before launching a special promotion. Or consider creating a sales report where we might want to display only the groups of products where the total sales exceeded $100. We already know how to group data using the GROUP BY
clause, but how do we filter those groups? That is where the HAVING
clause comes in.
Let’s explore the HAVING
clause in SQL. We will go step by step to:
Use the
HAVING
clause to filter out entire groups that do not meet certain criteria.Understand why
WHERE
does not work directly on aggregated values and why we needHAVING
instead.Recognize the difference between filtering individual rows (
WHERE
) and filtering grouped data (HAVING
).
Importance of filtering groups
We often group rows to perform aggregate calculations like COUNT
, SUM
, AVG
, MIN
, and MAX
. However, sometimes we want only those groups that meet a specific condition, such as having more than a certain number of items or reaching a certain total price. Filtering groups lets us focus on relevant clusters of data for more targeted insights.
The HAVING
clause
The HAVING
clause is used to filter results after we apply GROUP BY
. In SQL, the basic syntax of using the HAVING
clause is shown below:
Get hands-on with 1400+ tech skills courses.