CHAPTER 12
Filtering groups — the WHERE clause for aggregates.
Departments with more than 2 employees
SELECT department, COUNT(*) AS headcount FROM employees GROUP BY department HAVING COUNT(*) > 2;
| WHERE | HAVING | |
|---|---|---|
| Filter | Individual rows | Groups (after GROUP BY) |
| Runs | Before GROUP BY | After GROUP BY |
| Aggregates? | No - COUNT/AVG not allowed here | Yes - purpose-built for them |
| Example | WHERE salary > 60000 | HAVING AVG(salary) > 60000 |
❌ Common Mistake: Writing WHERE COUNT(*) > 2 throws an error. WHERE runs before aggregation — the COUNT values do not exist yet at that point in execution. Use HAVING.
✅ Interview Tip 'What is the difference between WHERE and HAVING?' is asked in almost every data-related SQL interview. Answer: WHERE filters rows before grouping; HAVING filters groups after aggregation.