Sobes.tech
Senior

What is the difference between HAVING and WHERE?

sobes.tech AI

Answer from AI

The main difference between HAVING and WHERE is the stage of data processing at which they are applied:

  • WHERE filters rows before grouping. It is applied to the raw data and limits the set of rows that will be included in aggregate functions and grouping.

  • HAVING filters groups after aggregate functions and grouping are performed. It is applied to the results of aggregation.

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 employees

Here, WHERE restricts the original rows, and HAVING filters the final groups.