WHERE vs HAVING
| Feature | WHERE |
HAVING |
|---|---|---|
| Purpose | Filters individual rows | Filters grouped results |
| Applied | Before GROUP BY |
After GROUP BY |
| Aggregate functions | Normally not allowed | Allowed |
Can work without GROUP BY |
Yes | Yes, but commonly used with it |
| Performance | Filters rows early | Filters after grouping |
Example data
Assume an Employees table contains:
| EmployeeName | Department | Salary |
|---|---|---|
| Ravi | IT | 50,000 |
| Priya | IT | 60,000 |
| Ahmed | HR | 40,000 |
| Meena | HR | 45,000 |
WHERE example
WHERE filters individual employees before grouping.
SELECT *
FROM Employees
WHERE Salary > 45000;
Result:
Ravi
Priya
HAVING example
HAVING filters departments after calculating their average salary.
SELECT Department, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 50000;
Result:
IT 55000
Using WHERE and HAVING together
SELECT Department, COUNT(*) AS EmployeeCount
FROM Employees
WHERE Salary >= 40000
GROUP BY Department
HAVING COUNT(*) >= 2;
Execution order:
WHERE → GROUP BY → HAVING → SELECT → ORDER BY
-
WHERE Salary >= 40000filters employees. -
GROUP BY Departmentcreates department groups. -
HAVING COUNT(*) >= 2filters those groups.
Easy memory tip
-
WHERE→ Filters rows -
HAVING→ Filters groups or aggregate results