Having Clause in SQL
HAVING Clause in SQL
The HAVING clause is used to filter groups created by the GROUP BY clause based on a condition.
Why use HAVING?
You use
WHEREto filter rows before grouping.You use
HAVINGto filter groups after aggregation.
Syntax:
SELECT column1, AGGREGATE_FUNCTION(column2)FROM table_nameGROUP BY column1HAVING condition;Example:
Suppose a Sales table:
| Region | Amount |
|---|---|
| East | 10 |
| East | 20 |
| West | 15 |
| West | 5 |
| East | 30 |
Query: Regions with total sales greater than 30
SELECT Region, SUM(Amount) AS TotalSalesFROM SalesGROUP BY RegionHAVING SUM(Amount) > 30;Result:
| Region | TotalSales |
|---|---|
| East | 60 |
Key points:
HAVINGworks only with grouped data.You can use aggregate functions (
SUM(),COUNT(), etc.) inHAVING.You can combine
WHEREandHAVINGin the same query.
Example:
SELECT Region, COUNT(*) AS NumSalesFROM SalesWHERE Amount > 5GROUP BY RegionHAVING COUNT(*) > 1;If you want, I can provide more examples or help with your specific use case!