(because sometimes you need to filter the results after SQL has already grouped the data)
π§ Quick Syntax
SELECT column, aggregate_function(column)
FROM table
GROUP BY column
HAVING condition;
This tells SQL:
“Group the data by a column, apply aggregate functions, and then filter the groups based on a condition.”
π Imagine You Have This sales
Table Again:
sale_id | product | quantity | sale_date |
---|---|---|---|
1 | Laptop | 3 | 2024-01-01 |
2 | Phone | 5 | 2024-01-01 |
3 | Laptop | 2 | 2024-01-02 |
4 | Phone | 3 | 2024-01-02 |
5 | Laptop | 4 | 2024-01-03 |
6 | Phone | 7 | 2024-01-03 |
Scenario: You want to find products where the total quantity sold is greater than 6.
π§ Using HAVING to Filter Grouped Data
Hereβs how to group by product and then use HAVING to filter groups based on the total quantity sold:
SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product
HAVING SUM(quantity) > 6;
β Result:
product | total_quantity |
---|---|
Phone | 15 |
π HAVING vs WHERE
Clause | When Itβs Used |
---|---|
WHERE | Filters rows before grouping |
HAVING | Filters groups after the data is grouped |
Where to use:
– Use WHERE
for filtering individual rows.
– Use HAVING
for filtering after the data is grouped.
π§ Recap
HAVING
is used to filter groups after data has been grouped withGROUP BY
.- It is especially useful with aggregate functions (like
SUM
,AVG
,COUNT
) to filter the results based on aggregated values. WHERE
filters data before grouping, whileHAVING
filters after grouping.