Ad space (banner)
🗄️SQL Lessons
Lesson 17 / 50

Filtering Aggregates with HAVING

This lesson covers filtering aggregated results with HAVING, and clarifies how it differs from WHERE. It's for anyone searching "SQL HAVING clause" or "SQL WHERE vs HAVING."

WHERE filters rows before aggregation happens; HAVING filters the results after GROUP BY has already summarized them — useful for something like "only show groups with 3 or more members."

The example groups by class_id, then uses HAVING COUNT(*) >= 2 to keep only classes with two or more students. The key point: a condition on an aggregate result belongs in HAVING, not WHERE.

A common early mistake is putting an aggregate function like COUNT() inside WHERE, which throws an error — WHERE runs before GROUP BY, and HAVING runs after, and once that execution order clicks, it's obvious why WHERE can't reference a count that doesn't exist yet. Needing "only groups above a certain size" comes up constantly in sales analysis and traffic reports, so knowing when to reach for HAVING instead of WHERE is an essential aggregation skill.

SQL
OUTPUT

💡 The SQL engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)