Sobes.tech
Middle

What is the difference between WHERE and HAVING 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 applies to individual table records.
  • HAVING filters already grouped data, meaning it is applied after GROUP BY and allows filtering of aggregated values.

Example:

SELECT department, COUNT(*) AS employee_count
FROM employees
WHERE salary > 50000  -- filter employees with salary above 50k
GROUP BY department
HAVING COUNT(*) > 10      -- select departments with more than 10 employees

Here, WHERE selects rows with salary above 50,000, and HAVING filters groups of departments with more than 10 employees.