HAVING filters groups. It works like WHERE, but on the summary rows that GROUP BY produces, so its condition can test a count, a total or an average.
SELECT column1, COUNT(*)FROM table_nameWHERE conditionGROUP BY column1HAVING group_conditionORDER BY column1;The examples use the tables from the example database.
Why WHERE is not enough
Section titled “Why WHERE is not enough”WHERE decides which rows go into the groups, so it runs before any totals exist. A condition on a total, such as “more than one invoice”, has to wait until the groups are formed, and that is the job of HAVING.
The productions with more than one invoice:
SELECT Productions.Title, COUNT(*) AS InvoicesFROM InvoicesINNER JOIN Productions ON Invoices.ProductionID = Productions.ProductionIDGROUP BY Productions.TitleHAVING COUNT(*) > 1;| Title | Invoices |
|---|---|
| The Lantern Keepers | 2 |
The departments whose average day rate is over 400:
SELECT Department, AVG(DayRate) AS AverageRateFROM CrewGROUP BY DepartmentHAVING AVG(DayRate) > 400ORDER BY AverageRate DESC;| Department | AverageRate |
|---|---|
| Production | 650 |
| Lighting | 520 |
| Camera | 480 |
Accounts averages 390, so it is filtered out.
WHERE and HAVING together
Section titled “WHERE and HAVING together”The two often work side by side: WHERE picks the rows, then HAVING picks the groups. The suppliers owed more than 3,000 in unpaid invoices:
SELECT Supplier, SUM(Amount) AS OwedFROM InvoicesWHERE PaidDate IS NULLGROUP BY SupplierHAVING SUM(Amount) > 3000;| Supplier | Owed |
|---|---|
| Ashby Camera Hire | 41,250.00 |
WHERE first sets aside the paid invoices. The remaining rows form two groups, Ashby Camera Hire with 41,250 and Kestrel Catering with 2,940, and HAVING keeps only the first.