What is the difference between WHERE and HAVING?
Options
- There is no difference between them, apart from their names
- WHERE filters rows before grouping; HAVING filters the groups (Correct option)
- HAVING is always faster than WHERE in every database
- WHERE works only together with JOINs in a query
Answer
WHERE filters rows before grouping; HAVING filters groups after aggregation
Why
SQL runs WHERE first: it removes individual rows. Then GROUP BY makes groups and aggregates (COUNT, SUM...). Then HAVING filters the groups using those aggregate results.
Example: departments with more than 5 active employees.
SELECT dept, COUNT(*)
FROM employees
WHERE active = true -- filter rows
GROUP BY dept
HAVING COUNT(*) > 5; -- filter groupsRemember
WHERE filters rows, HAVING filters groups.