Beginner

546. JOIN with HAVING

Learn how HAVING filters aggregated results produced after joining tables.

📘 Lesson 546 of 728 ⏱ 13 min 🎯 Intermediate

HAVING filters groups after aggregation. When used with JOINs, it can restrict results based on calculated values such as total sales or order counts.

Business questions often require filtering groups after calculating totals or counts.

Find customers whose total order value is greater than ₹100,000.

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

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

  • HAVING filters groups.
  • WHERE filters rows before aggregation.
  • HAVING is commonly used with aggregate functions.
  • JOIN can provide the data being aggregated.
  • Use the correct filtering stage.
Why use HAVING instead of WHERE for aggregate filters?

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

Can HAVING be used after a JOIN?

Yes. HAVING can filter aggregated groups created from joined tables.

Have you finished this lesson?

Introduction to SQL – All Lessons