SQL HAVING
Filter aggregated groups after GROUP BY.
How it works
WHERE filters individual source rows. HAVING filters groups after aggregation. That difference matters whenever your condition depends on COUNT, SUM, AVG or another aggregate.
You can use WHERE and HAVING together: WHERE narrows the source data first, then HAVING keeps only the aggregated groups you care about.
Show only materials with more than five transactions or suppliers whose average lead time exceeds the target.
The pattern
SELECT group_column, COUNT(*) AS n
FROM table
GROUP BY group_column
HAVING COUNT(*) > 1;Example
SELECT CustomerID, COUNT(*) AS Orders
FROM Orders
GROUP BY CustomerID
HAVING COUNT(*) > 1;Run the example
Edit the query and run it against the built-in demo tables. Nothing is sent to a server.
The learning runner supports SELECT, WHERE, LIKE, IN, BETWEEN, GROUP BY, HAVING, JOIN, aggregates, ORDER BY and LIMIT. Advanced lessons explain additional production SQL concepts even when the mini runner does not execute that syntax.
Which clause filters aggregate results?
Progress is stored only in this browser. No account required.