Sobes.tech
Junior — Middle

What is the difference between the use of HAVING and WHERE conditions in SQL?

sobes.tech AI

Answer from AI

In SQL, WHERE and HAVING are used for filtering, but at different stages of data processing:

  • WHERE filters rows before grouping (before GROUP BY). It limits the dataset that will be aggregated.
  • HAVING filters groups after aggregation. It is used for conditions on aggregate functions, such as SUM(), COUNT().

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 such employees

Thus, WHERE works with individual records, while HAVING works with the results of aggregation.