The HAVING clause is used to filter grouped records after the GROUP BY clause has been applied.
Key difference:
- WHERE → filters rows before grouping
- HAVING → filters groups after aggregation
Basic syntax:
HAVINGis mainly used with aggregate functions likeCOUNT(),SUM(),AVG(),MIN(),MAX().
Step 1: Example table
Employees Table
| EmployeeID | Name | Department | Salary |
|---|---|---|---|
| 1 | John | IT | 5000 |
| 2 | Jane | HR | 4500 |
| 3 | Mike | IT | 6000 |
| 4 | Sara | HR | 4700 |
| 5 | Tom | IT | 5200 |
Step 2: HAVING with COUNT()
Find departments that have more than 2 employees:
Result:
| Department | TotalEmployees |
|---|---|
| IT | 3 |
Step 3: HAVING with SUM()
Find departments where total salary is greater than 10,000:
Result:
| Department | TotalSalary |
|---|---|
| IT | 15200 |
Step 4: HAVING with AVG()
Find departments where average salary is above 5,000:
Result:
| Department | AverageSalary |
|---|---|
| IT | 5066.67 |
Step 5: WHERE vs HAVING (important difference)
❌ Wrong (aggregate in WHERE):
❌ This will cause an error.
Correct (aggregate in HAVING):
Step 6: Using WHERE and HAVING together
Filter rows first, then filter groups:
Explanation:
- WHERE Salary > 4800 → filters employees first
- GROUP BY Department → groups remaining rows
- HAVING COUNT(*) >= 2 → filters grouped results
