Senior
How does HAVING differ from WHERE?
sobes.tech AI
Answer from AI
In SQL, the WHERE clause filters rows before grouping, meaning it is applied to the raw data. HAVING, on the other hand, filters groups formed after applying GROUP BY.
Example:
SELECT department, COUNT(*) as emp_count
FROM employees
WHERE salary > 50000 -- filter employees with salary > 50000
GROUP BY department
HAVING COUNT(*) > 5 -- select departments with more than 5 employees
Here, first employees with a salary above 50000 are selected (WHERE), then data is grouped by departments, and only those groups with more than 5 employees are selected (HAVING).