Where Vs Having in SQL
Great question! Both WHERE and HAVING are used to filter data in SQL, but they serve different purposes and are used in different contexts.
WHERE vs HAVING
| Aspect | WHERE | HAVING |
|---|---|---|
| Purpose | Filters rows before grouping (on individual rows) | Filters groups after grouping (on aggregated data) |
| Used with | SELECT, UPDATE, DELETE statements | GROUP BY clause (used with aggregate functions) |
| Applies to | Individual rows | Groups (aggregated rows) |
| Can use aggregate functions? | No | Yes (e.g., COUNT(), SUM(), AVG()) |
| Example filtering | WHERE Age > 30 | HAVING COUNT(*) > 5 |
Examples
Using WHERE
SELECT Department, EmployeeName, SalaryFROM EmployeesWHERE Salary > 50000; -- Filters rows before groupingUsing HAVING
SELECT Department, COUNT(*) AS EmployeeCountFROM EmployeesGROUP BY DepartmentHAVING COUNT(*) > 5; -- Filters groups after aggregationSummary
Use
WHEREto filter rows before aggregation.Use
HAVINGto filter groups after aggregation.
Need examples combining both or explanations of when to choose which?