Sobes.tech
Middle

Standard SQL question: what is the difference between WHERE and HAVING?

sobes.tech AI

Answer from AI

The main difference between WHERE and HAVING in SQL is the stage at which they filter data:

  • WHERE filters rows before grouping. It is used to restrict the initial data set.
  • HAVING filters groups after applying aggregate functions and grouping (GROUP BY).

Example:

SELECT department, COUNT(*) as emp_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

Here, WHERE limits the initial rows, and HAVING filters the final groups.