Course contentsShow
← Data Science
Lesson 914 of 2,14523. SQL Aggregation and GroupingFree lesson

HAVING: Filtering Aggregated Results

Using HAVING to filter groups based on aggregate function results like COUNT, SUM, or AVG.

HAVING: Filtering Aggregated Results

What you'll learn: How to use the HAVING clause to filter groups based on calculated aggregate values like COUNT, SUM, or AVG.

The Core Idea

Now that you understand WHERE filters individual rows before grouping, HAVING does something different: it filters after groups have been formed and aggregates calculated. Think of HAVING as the gatekeeper that decides which groups make it into your final results.

Imagine sorting fruit into baskets by type (GROUP BY), then counting each basket (aggregate function). WHERE would let you exclude rotten apples before sorting. HAVING lets you exclude baskets with fewer than 10 pieces after counting—you're filtering based on the count itself.

When to Use HAVING

Use HAVING whenever your filter condition involves an aggregate function result:

SELECT department, COUNT(*) as employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

This returns only departments with more than 5 employees. You couldn't use WHERE here because COUNT(*) doesn't exist until after grouping.

SELECT product_category, AVG(price) as avg_price
FROM products
GROUP BY product_category
HAVING AVG(price) > 50;

This shows only categories where the average price exceeds $50.

The Pattern

HAVING always works with GROUP BY and aggregate functions. It answers questions like "which groups have a total exceeding X?" or "which categories have an average below Y?"

Key Takeaway: HAVING filters groups based on aggregate function results (COUNT, SUM, AVG, etc.) after grouping, making it essential for analyzing grouped data where you need to exclude groups that don't meet aggregate criteria.