HAVING is like WHERE but operates on grouped records.
HAVING requires that a GROUP BY clause is present.
Groups that meet the HAVING criteria will be returned.
List all countries with more than 2 suppliers.
SELECT Country, COUNT(Id) AS Suppliers
FROM Supplier
GROUP BY Country
HAVING COUNT(Id) > 2
| Country | Suppliers |
|---|---|
| France | 3 |
| Germany | 3 |
| USA | 4 |
HAVING syntax.
SELECT column-names FROM table-name WHERE condition GROUP BY column-names HAVING condition
HAVING syntax with ORDER BY.
SELECT column-names FROM table-name WHERE condition GROUP BY column-names HAVING condition ORDER BY column-names
| CUSTOMER |
|---|
| Id |
| FirstName |
| LastName |
| City |
| Country |
| Phone |
SELECT Country, COUNT(Id) AS Customers
FROM Customer
GROUP BY Country
HAVING COUNT(Id) > 10
| Country | Customers |
|---|---|
| France | 11 |
| Germany | 11 |
| USA | 13 |
| CUSTOMER |
|---|
| Id |
| FirstName |
| LastName |
| City |
| Country |
| Phone |
SELECT Country, COUNT(Id) AS Customers
FROM Customer
WHERE Country <> 'USA'
GROUP BY Country
HAVING COUNT(Id) >= 9
ORDER BY COUNT(Id) DESC
| Country | Customers |
|---|---|
| France | 11 |
| Germany | 11 |
| Brazil | 9 |
| ORDER |
|---|
| Id |
| OrderDate |
| OrderNumber |
| CustomerId |
| TotalAmount |
| CUSTOMER |
|---|
| Id |
| FirstName |
| LastName |
| City |
| Country |
| Phone |
SELECT FirstName, LastName,
CONVERT(DECIMAL(10,2), AVG(TotalAmount)) AS 'Average Order'
FROM [Order] O
JOIN Customer C ON O.CustomerId = C.Id
GROUP BY FirstName, LastName
HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200
Note: CONVERT formats the average value to 2 decimals.
| FirstName | LastName | Average Order |
|---|---|---|
| Miguel | Angel Paolino | 1081.22 |
| Isabel | de Castro | 1063.42 |
| Alexander | Feuer | 1008.44 |
| Thomas | Hardy | 1062.04 |
| Pirkko | Koskitalo | 1107.81 |
| Janete | Limeira | 1174.95 |
| Antonio | Moreno | 1073.62 |
| Rita | Müller | 1065.39 |
| José | Pedro Freyre | 1183.01 |
| Carine | Schmitt | 1057.39 |