Junior — Middle
What is the difference between the WHERE and HAVING conditions when working with SQL queries?
sobes.tech AI
Answer from AI
WHERE and HAVING are filtering conditions in SQL, but they are applied at different stages of data processing.
WHEREfilters rows before grouping. It is used to select records at the source data level.HAVINGfilters groups formed by theGROUP BYoperator. It is applied after aggregation.
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 employees
Here, employees with a salary above 50000 are selected first (WHERE), then data is grouped by departments, and afterwards, only those departments with more than 10 employees are selected (HAVING).