Junior — Middle
What is the difference between the WHERE and HAVING operators in SQL queries?
sobes.tech AI
Answer from AI
The WHERE and HAVING operators in SQL are used for filtering data, but they are applied at different stages of query processing:
-
WHERE filters rows before grouping. It is applied to the raw data and limits the set of rows that will be processed further.
-
HAVING filters groups after applying aggregate functions and grouping (GROUP BY). It is used to restrict groups based on conditions related to aggregates.
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
Here, first employees with a salary above 50000 are selected (WHERE), then data is grouped by departments, and among these groups, only those with more than 10 employees are chosen (HAVING).