SQL HAVING Clause
HAVING filters groups after GROUP BY has done its work. Use it for conditions on aggregates, like “customers with more than one order”.
Updated December 1, 2026
Syntax
SELECT group_column, AGGREGATE(column)
FROM table_name
GROUP BY group_column
HAVING condition_on_aggregate;
Keep only big groups
Categories with more than three drinks.
SELECT category, COUNT(*) AS drinks
FROM drinks
GROUP BY category
HAVING COUNT(*) > 3;
| category | drinks |
|---|---|
| coffee | 5 |
Find repeat customers
Customer ids with more than one order.
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1;
| customer_id | orders |
|---|---|
| 1 | 3 |
| 2 | 2 |
WHERE and HAVING together
WHERE removes rows first (only caffeinated drinks), then HAVING removes groups (average price above $4.50).
SELECT category, ROUND(AVG(price), 2) AS avg_price
FROM drinks
WHERE caffeinated = 1
GROUP BY category
HAVING AVG(price) > 4.5;
| category | avg_price |
|---|---|
| tea | 5 |
Common mistakes
- Putting aggregate conditions in
WHERE:WHERE COUNT(*) > 1is an error. - Using
HAVINGfor plain row filters. It works, butWHEREis clearer and lets the database skip rows earlier.
Practice HAVING Clause interactively
Write real queries in your browser and get instant feedback in the lesson “HAVING” (Unit 4). New learners can start free from the first lesson.
Frequently asked questions
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping. HAVING filters groups after aggregation. A query can use both.
Can HAVING use a column alias?
SQLite and MySQL allow it, but PostgreSQL and SQL Server don’t. Repeating the aggregate, like HAVING COUNT(*) > 1, works everywhere.