Sobes.tech
Intern

How does the WHERE operator differ from the HAVING operator?

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 limits the dataset that will be aggregated.
  • HAVING filters groups after aggregation. It is used together with GROUP BY to select groups based on conditions on aggregate functions.

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 salary above 50000 are selected (WHERE), then data is grouped by departments, and only those groups where the number of employees is greater than 10 are selected (HAVING).