Sobes.tech
Middle

What is the difference between HAVING and WHERE?

sobes.tech AI

Answer from AI

The main difference between WHERE and HAVING in SQL:

  • WHERE filters rows before grouping. It applies to individual table records.
  • HAVING filters groups after aggregate functions (GROUP BY) are executed.

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

Here, WHERE selects rows for grouping, and HAVING filters groups based on aggregate conditions.