SQL HAVING
HAVING filters groups, after GROUP BY has run. Use it when your condition involves an aggregate: categories with an average price over 50, countries with more than 15 customers.
A query can have both: WHERE removes rows first, then GROUP BY groups what is left, then HAVING removes groups.
Syntax
SELECT column, AGG(x) FROM table_name GROUP BY column HAVING AGG(x) > value;
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
having.sql · PostgreSQL
Loading editor…
Examples
1. Groups with a minimum size
SELECT country, COUNT(*) FROM customers GROUP BY country HAVING COUNT(*) > 15;
Only large countries.
2. WHERE and HAVING together
SELECT category, ROUND(AVG(price), 2) FROM products WHERE stock > 0 GROUP BY category HAVING AVG(price) > 50;
In-stock products only, then expensive categories.
Common mistakes
- Using HAVING for row conditions that belong in WHERE (it works but is slower and less clear).
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Challenge · 20 pts
Return each country with more than 15 customers, and its customer count.
challenge.sql · PostgreSQL
Loading editor…
FAQ
Can HAVING use a column alias?
Not in PostgreSQL. Repeat the aggregate expression.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.