4.4 — Filtering Groups with HAVING
What You'll Learn
- How to use the
HAVING
clause to filter groups in SQL - How this compares to filtering results in Excel PivotTables
Why HAVING?
Here is the sales data we'll use in our examples:
Product | Amount | SaleDate |
---|---|---|
Apples | 120 | 2024-05-01 |
Apples | 90 | 2024-05-02 |
Oranges | 80 | 2024-05-01 |
Oranges | 70 | 2024-05-03 |
Bananas | 60 | 2024-05-02 |
Bananas | 50 | 2024-05-03 |
Pears | 40 | 2024-05-01 |
Pears | 30 | 2024-05-03 |
In Excel, you might filter a PivotTable to show only products with sales above a certain amount. In SQL, use HAVING
to filter after grouping.
Example: Show only products with total sales over 200
sql
SELECT Product, SUM(Amount) AS Total_Sales
FROM sales
GROUP BY Product
HAVING SUM(Amount) > 200;
HAVING
works likeWHERE
, but for aggregated/grouped results.
Combining WHERE and HAVING
- Use
WHERE
to filter rows before grouping. - Use
HAVING
to filter groups after aggregation.
Example: Only include sales from May, then show products with high totals
sql
SELECT Product, SUM(Amount) AS Total_Sales
FROM sales
WHERE SaleDate >= Date '2024-05-01' AND SaleDate <= Date '2024-05-31'
GROUP BY Product
HAVING SUM(Amount) > 200;
Tip: You can also use the alias of the calculated column with HAVING
:
sql
...
HAVING Total_Sales > 200;
Key Points
- Use
HAVING
to filter after grouping and aggregation. - Use
WHERE
to filter before grouping.
Next Steps
In the next module, you’ll learn practical techniques for real-world business analysis.