Skip to content

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:

ProductAmountSaleDate
Apples1202024-05-01
Apples902024-05-02
Oranges802024-05-01
Oranges702024-05-03
Bananas602024-05-02
Bananas502024-05-03
Pears402024-05-01
Pears302024-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 like WHERE, 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.