Middle+
What is the difference between WHERE and HAVING?
sobes.tech AI
Answer from AI
WHERE and HAVING are filtering conditions in SQL, but they are applied at different stages of data processing:
-
WHERE filters rows before grouping. It is applied to the raw data and limits the set of rows that will be processed further.
-
HAVING filters groups after aggregate functions and grouping (GROUP BY) are performed. It is used to restrict groups based on aggregate conditions.
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
Here, employees with a salary above 50000 are selected first (WHERE), then they are grouped by department, and only those groups with more than 10 employees are chosen (HAVING).