The HAVING Clause
The HAVING clause filters groups created by GROUP BY — like WHERE, but for aggregated data.
💡 HAVING is used after GROUP BY to filter groups based on aggregate conditions.
Basic Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1
HAVING aggregate_condition;
Example
SELECT department, COUNT(*) AS employee_count, ROUND(AVG(salary), 2) AS avg_salary
FROM employees
WHERE hire_date >= '2020-01-01'
GROUP BY department
HAVING COUNT(*) > 1
ORDER BY avg_salary DESC;
WHERE vs HAVING
| Clause | Filters | When | Can Use Aggregates |
|---|---|---|---|
| WHERE | Individual rows | Before GROUP BY | No |
| HAVING | Groups | After GROUP BY | Yes |
✏️ Exercise: Write a query that uses HAVING to find departments with more than 2 employees
See Solution
SELECT department, COUNT(*) AS count
FROM employees
GROUP BY department
HAVING COUNT(*) > 2
ORDER BY count DESC;
✅ Key Takeaways
- HAVING filters groups after aggregation
- Use with aggregate functions like COUNT, SUM, AVG, MIN, MAX
- WHERE filters individual rows BEFORE grouping
- HAVING filters groups AFTER grouping
- ORDER BY comes last after GROUP BY and HAVING