Sobes.tech
Middle+

What is HAVING and how does it differ from WHERE?

sobes.tech AI

Answer from AI

WHERE filters rows before grouping, that is, it applies to the raw data. HAVING filters groups after applying aggregate functions, that is, to the result of GROUP BY.

Example:

SELECT department, COUNT(*) AS employees
FROM employees
WHERE salary > 50000  -- filter by salary for individual rows
GROUP BY department
HAVING COUNT(*) > 10    -- filter by number of employees in the department

Here, WHERE selects employees with a salary above 50000, and HAVING filters departments with more than 10 such employees.