Middle
What is the difference between HAVING and WHERE in SQL?
sobes.tech AI
Answer from AI
The main difference between HAVING and WHERE in SQL is the stage at which they are applied during data processing and the data they operate on:
-
WHERE filters rows before grouping. It is applied to the raw data and limits the set of rows that will be included in aggregate functions and grouping.
-
HAVING filters groups after aggregate functions and grouping are performed. It is applied to the results of the grouping and allows filtering groups based on aggregate conditions.
Example:
SELECT department, COUNT(*) as emp_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
Here, WHERE filters employee rows with salaries above 50000, and HAVING filters department groups where there are more than 10 such employees.