Middle
Explain 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 limits the dataset that will be included in aggregate functions.
- HAVING filters groups after applying aggregate functions (e.g., SUM, COUNT).
Example:
SELECT department, COUNT(*) as emp_count
FROM employees
WHERE salary > 50000 -- filter employees with salary above 50000
GROUP BY department
HAVING COUNT(*) > 10; -- select departments with more than 10 employees
Thus, WHERE works with individual rows, while HAVING works with aggregated groups.