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

CountryCustomers
India2
UK2

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

EmployeeIDOrdersTotal
23931.15

WHERE vs HAVING

WHEREHAVING
Filtersindividual rowsgroups
Runsbefore GROUP BYafter GROUP BY
Aggregates allowed?noyes
Performancereduces rows early: prefer it whenever possibleuse only for conditions on aggregates