Skip to content

SQL HAVING Clause

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_name
WHERE condition
GROUP BY column1
HAVING group_condition
ORDER BY column1;

The examples use the tables from the example database.

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 Invoices
FROM Invoices
INNER JOIN Productions ON Invoices.ProductionID = Productions.ProductionID
GROUP BY Productions.Title
HAVING COUNT(*) > 1;
Title Invoices
The Lantern Keepers 2

The departments whose average day rate is over 400:

SELECT Department, AVG(DayRate) AS AverageRate
FROM Crew
GROUP BY Department
HAVING AVG(DayRate) > 400
ORDER BY AverageRate DESC;
Department AverageRate
Production 650
Lighting 520
Camera 480

Accounts averages 390, so it is filtered out.

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 Owed
FROM Invoices
WHERE PaidDate IS NULL
GROUP BY Supplier
HAVING 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.