Sobes.tech
Junior — Middle

What are the differences between the HAVING and WHERE clauses in SQL queries, and in which cases are they used?

sobes.tech AI

Answer from AI

The WHERE and HAVING commands in SQL are used for filtering data but are applied at different stages of query processing.

  • 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 or grouping.

  • HAVING filters groups after applying aggregate functions and grouping. It is used for conditions on aggregated values.

Example:

SELECT department, COUNT(*) AS employee_count
FROM employees
WHERE salary > 50000  -- filtering individual employees
GROUP BY department
HAVING COUNT(*) > 10;    -- filtering departments with more than 10 employees

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

What are the differences between the HAVING and WHERE… - sobes.tech