🔍 SQL HAVING Clause – Filter Aggregated Data with Precision
The SQL
HAVINGclause is used to filter grouped records created by theGROUP BYclause. It’s likeWHERE, 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?
WHEREfilters rows before grouping.HAVINGfilters 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:
| region | amount |
|---|---|
| East | 400 |
| West | 300 |
| East | 700 |
| West | 200 |
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:
| region | total_sales |
|---|---|
| East | 1100 |
📊 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
| Feature | WHERE Clause | HAVING Clause |
|---|---|---|
| Filters on | Individual rows | Groups created by GROUP BY |
| Use with | Any column | Only after aggregation |
| Example usage | amount > 100 | SUM(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
HAVINGto filter results afterGROUP BYaggregation - Works with functions like
SUM(),AVG(),COUNT(), etc. - Combine
WHEREandHAVINGfor efficient querying - Crucial for generating summary reports with filters

