Junior — Middle
Explain the differences between the HAVING operator and the WHERE condition in SQL and in which cases they should be used?
sobes.tech AI
Answer from AI
In SQL, the WHERE condition filters rows before grouping, while HAVING filters after grouping.
- WHERE applies to individual table rows and limits the dataset that will be aggregated.
- HAVING applies to the results of aggregate functions and filters the groups formed by the GROUP BY statement.
Example:
SELECT department, COUNT(*) as employee_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
Use WHERE to filter the raw data, and HAVING to filter the aggregated results.