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

HAVING Clause Fundamentals

Learn what HAVING does and why it's needed to filter aggregated results after GROUP BY operations.

HAVING Clause Fundamentals

You'll learn how to filter grouped results using HAVING, which solves a problem WHERE can't handle.

Why WHERE Isn't Enough

When you use GROUP BY to aggregate data (like counting customers per region or averaging sales by product), you often want to filter those aggregated results. Here's the catch: WHERE filters rows before grouping happens, so it can't see aggregate values like totals or averages.

Example scenario: You want to find customers who've made more than 5 purchases. You need to group by customer, count their orders, then filter groups where the count exceeds 5. WHERE can't do this because it runs before COUNT() is calculated.

Enter HAVING

HAVING is designed specifically to filter groups after aggregation. It comes after GROUP BY in your query and uses aggregate functions in its conditions.

Think of it this way: WHERE is a bouncer checking IDs at the door (individual rows), while HAVING is a VIP coordinator who only lets groups in if they meet certain criteria (like having enough members).

Syntax Pattern

SELECT column, COUNT(*)
FROM table
WHERE condition_on_rows
GROUP BY column
HAVING condition_on_aggregates

Simple Example

SELECT region, COUNT(*) as customer_count
FROM customers
GROUP BY region
HAVING COUNT(*) > 100

This groups customers by region, then only shows regions with more than 100 customers.

HAVING vs WHERE

  • WHERE: Filters individual rows before grouping
  • HAVING: Filters groups after aggregation

You can use both in the same query—WHERE reduces data first, then HAVING filters the final grouped results.

Key Takeaway: Use HAVING to filter aggregated results after GROUP BY—it's the only way to apply conditions to computed values like COUNT(), SUM(), or AVG().