T
Tech Town
Log InSign Up Free
← Back to Blog

June 17, 2025 · admin

HAVING

๐Ÿ” 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