Middle
What is the difference between WHERE and HAVING 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 applies to individual table records.HAVINGfilters already grouped data, meaning it is applied afterGROUP BYand allows filtering of aggregated values.
Example:
SELECT department, COUNT(*) AS employee_count
FROM employees
WHERE salary > 50000 -- filter employees with salary above 50k
GROUP BY department
HAVING COUNT(*) > 10 -- select departments with more than 10 employees
Here, WHERE selects rows with salary above 50,000, and HAVING filters groups of departments with more than 10 employees.