Beginner

599. JOIN with HAVING

Learn how HAVING filters grouped results produced after a JOIN.

📘 Lesson 599 of 728 ⏱ 14 min 🎯 Intermediate

HAVING filters groups after aggregation. When used with JOINs, it can restrict the final result to entities whose aggregated related data meets a business condition.

Many analytical questions require filtering based on totals, counts, or averages rather than individual rows.

Find customers whose total sales exceed 100,000.

SQL
SELECT
    c.CustomerName,
    SUM(o.OrderAmount) AS TotalSales
FROM Customers c
INNER JOIN Orders o
    ON c.CustomerID = o.CustomerID
GROUP BY
    c.CustomerName
HAVING SUM(o.OrderAmount) > 100000;

Used in customer segmentation, sales reporting, KPI analysis, and financial dashboards.

  • WHERE filters rows before grouping.
  • HAVING filters groups after aggregation.
  • JOIN can provide the related records being aggregated.
  • HAVING is useful for aggregate-based business rules.
  • The query should use GROUP BY when required by the SQL dialect.
Why use HAVING instead of WHERE for SUM?

HAVING filters aggregated groups, while WHERE filters individual rows before aggregation.

Can HAVING be used with JOIN?

Yes. HAVING can filter grouped results created from data combined through JOINs.

Have you finished this lesson?

Introduction to SQL – All Lessons