Sobes.tech
Junior — Middle

What is the difference between the WHERE and HAVING conditions when working with SQL queries?

sobes.tech AI

Answer from AI

In SQL, the WHERE and HAVING conditions are used for filtering data but are applied at different stages of query processing:

  • WHERE filters rows before grouping and aggregation. It limits the dataset that will be used in the query.
  • HAVING filters groups after applying aggregate functions (e.g., SUM, COUNT, AVG). It is used to restrict 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 selects employees with a salary above 50000, and HAVING filters departments with more than 10 such employees.