What is the difference between "WHERE" and "HAVING" clauses in SQL?
2025
What is the difference between "WHERE" and "HAVING" clauses in SQL?
Answer: B. WHERE filters rows before grouping, HAVING filters groups after aggregation — Answer: WHERE filters rows before grouping; HAVING filters groups after aggregation. WHERE applies to individual rows and is evaluated before GROUP BY. It…
- A.
Both are the same
- B.
WHERE filters rows before grouping, HAVING filters groups after aggregation
- C.
HAVING filters rows before grouping, WHERE filters groups after aggregation
- D.
WHERE can be used with aggregate functions
Attempted by 945 students.
Show answer & explanation
Correct answer: B
Answer: WHERE filters rows before grouping; HAVING filters groups after aggregation.
WHERE applies to individual rows and is evaluated before GROUP BY. It cannot use aggregate functions (for example, WHERE COUNT(*) > 1 is invalid).
HAVING is evaluated after aggregation (after GROUP BY) and can use aggregate functions to filter groups.
If you need to filter on aggregated values but cannot use HAVING for some reason, compute the aggregates in a subquery or CTE and apply WHERE in the outer query.
Example: SELECT dept, COUNT(*) AS cnt FROM employees WHERE salary > 50000 GROUP BY dept HAVING COUNT(*) > 5;
Summary: Use WHERE to limit which rows enter aggregation; use HAVING to limit which groups appear in the final aggregated result.