iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL HAVING

HAVING filters groups after aggregation. It's WHERE for the output of GROUP BY.

Example

SQL
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
HAVING COUNT(*) > 5
ORDER BY customers DESC;

"Show countries that have more than 5 customers" — the filter is on the aggregate result, which WHERE can't see.

WHERE vs HAVING

Need to filterUse
Individual rows before groupingWHERE
Whole groups after aggregationHAVING
BothBoth — WHERE first, then HAVING
SQL
SELECT country, COUNT(*) AS active_customers
FROM customers
WHERE active = 1       -- per-row filter
GROUP BY country
HAVING COUNT(*) >= 10;  -- per-group filter

Common pitfall

Putting an aggregate in WHERE is a syntax error:

SQL
-- ✗ Error: aggregate not allowed in WHERE
WHERE COUNT(*) > 5
-- ✓ Move it to HAVING
HAVING COUNT(*) > 5
Tip: If HAVING only references columns in GROUP BY (not aggregates), prefer WHERE — it filters earlier and is usually faster.

Example

Example
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
HAVING COUNT(*) > 5;
Try it Yourself »

Exercise

Filter the groups, keeping only those with more than 5 customers.

GROUP BY country COUNT(*) > 5

Test yourself

Q1. HAVING filters…
Q2. You cannot use an aggregate in…
Q3. When HAVING references only GROUP BY columns, prefer…

Discussion

Loading…