Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

The main difference between WHERE and HAVING in SQL:

  • WHERE filters rows before grouping (GROUP BY). It applies to individual table records.
  • HAVING filters groups after grouping is performed. It is used for conditions on aggregate functions (e.g., COUNT, SUM).

Example:

SELECT department, COUNT(*) as employee_count
FROM employees
WHERE salary > 50000    -- filter employees with salary above 50000
GROUP BY department
HAVING COUNT(*) > 10     -- select departments with more than 10 employees

Here, WHERE selects rows for grouping, and HAVING filters the already grouped data.

What is the difference between the HAVING and WHERE… - sobes.tech