Junior — Middle
What is the difference between the use of HAVING and WHERE conditions in SQL?
sobes.tech AI
Answer from AI
In SQL, WHERE and HAVING are used for filtering, but at different stages of data processing:
WHEREfilters rows before grouping (beforeGROUP BY). It limits the dataset that will be aggregated.HAVINGfilters groups after aggregation. It is used for conditions on aggregate functions, such asSUM(),COUNT().
Example:
SELECT department, COUNT(*) as employee_count
FROM employees
WHERE salary > 50000 -- filter employees with salary > 50000
GROUP BY department
HAVING COUNT(*) > 10 -- select departments with more than 10 such employees
Thus, WHERE works with individual records, while HAVING works with the results of aggregation.