🔍 SQL HAVING Clause – Filter Aggregated Data with Precision

The SQL HAVING clause is used to filter grouped records created by the GROUP BY clause. It’s like WHERE, but it works after aggregation.

When you want to filter based on aggregate values such as total sales, average scores, or counts, HAVING is your go-to clause.


📘 What is SQL HAVING?

  • WHERE filters rows before grouping.
  • HAVING filters groups after aggregation.

📌 You must use HAVING when filtering on aggregate functions like SUM(), AVG(), COUNT(), MAX(), and MIN().


🧾 Syntax of SQL HAVING

SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;

✅ Example: Filter Regions with Sales > 1000

Suppose you have a sales table:

regionamount
East400
West300
East700
West200

This query returns regions with total sales > 1000:

SELECT region, SUM(amount) AS total_sales
FROM sales
GROUP BY region
HAVING SUM(amount) > 1000;

🧾 Result:

regiontotal_sales
East1100

📊 Real-World Use Cases for HAVING

  • 📦 Products with total quantity sold above a threshold
  • 👥 Customer segments with more than X users
  • 🧾 Departments with average expenses over budget
  • 📈 Cities with more than 100 sales per month

🔄 HAVING vs WHERE – Key Differences

FeatureWHERE ClauseHAVING Clause
Filters onIndividual rowsGroups created by GROUP BY
Use withAny columnOnly after aggregation
Example usageamount > 100SUM(amount) > 1000

📌 You can use both in a single query:

SELECT region, SUM(amount) AS total_sales
FROM sales
WHERE amount > 100
GROUP BY region
HAVING SUM(amount) > 1000;

🎯 Using Multiple Conditions in HAVING

HAVING SUM(amount) > 1000 AND COUNT(*) > 5

✔️ You can use AND, OR, and NOT with HAVING, just like in WHERE.


💡 HAVING Without GROUP BY

Yes, you can use HAVING even without GROUP BY to filter on aggregated results:

SELECT COUNT(*) AS total_orders
FROM orders
HAVING COUNT(*) > 1000;

🧠 This acts like a WHERE for a single aggregate result.


📝 Summary

  • Use HAVING to filter results after GROUP BY aggregation
  • Works with functions like SUM(), AVG(), COUNT(), etc.
  • Combine WHERE and HAVING for efficient querying
  • Crucial for generating summary reports with filters