Careeroza
HAVING
The SQL HAVING Clause
HAVING was added because WHERE cannot be used with aggregate functions. WHERE filters rows before grouping; HAVING filters groups after grouping.
SELECT column_name(s), aggregate_function(column)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);Example
Example
Countries with more than one customer:
SELECT Country, COUNT(*) AS Customers
FROM Customers
GROUP BY Country
HAVING COUNT(*) > 1;Result: 2 rows
| Country | Customers |
|---|---|
| India | 2 |
| UK | 2 |
WHERE and HAVING Together
Example
Among orders from 2024-02 onwards, employees who handled orders worth more than 300 in total:
SELECT EmployeeID, COUNT(*) AS Orders, SUM(Amount) AS Total
FROM Orders
WHERE OrderDate >= '2024-02-01' AND EmployeeID IS NOT NULL
GROUP BY EmployeeID
HAVING SUM(Amount) > 300;Result: 1 row
| EmployeeID | Orders | Total |
|---|---|---|
| 2 | 3 | 931.15 |
WHERE vs HAVING
WHERE | HAVING | |
|---|---|---|
| Filters | individual rows | groups |
| Runs | before GROUP BY | after GROUP BY |
| Aggregates allowed? | no | yes |
| Performance | reduces rows early: prefer it whenever possible | use only for conditions on aggregates |