Junior — Middle
What is the purpose of the HAVING operator in SQL and how does it differ from WHERE?
sobes.tech AI
Answer from AI
The HAVING operator in SQL is used to filter results after data has been grouped using GROUP BY. It allows setting conditions on aggregate functions (such as SUM, COUNT), whereas WHERE filters rows before grouping.
Example:
SELECT department, COUNT(*) as employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
Here, HAVING selects only those departments with more than 5 employees.
In summary:
- WHERE filters individual rows before grouping.
- HAVING filters grouped data after aggregation.