Repaso
EspaƱol

What is the difference between WHERE and HAVING?

Options

  1. There is no difference between them, apart from their names
  2. WHERE filters rows before grouping; HAVING filters the groups (Correct option)
  3. HAVING is always faster than WHERE in every database
  4. WHERE works only together with JOINs in a query

Answer

WHERE filters rows before grouping; HAVING filters groups after aggregation

Why

SQL runs WHERE first: it removes individual rows. Then GROUP BY makes groups and aggregates (COUNT, SUM...). Then HAVING filters the groups using those aggregate results.

Example: departments with more than 5 active employees.

SELECT dept, COUNT(*)
FROM employees
WHERE active = true          -- filter rows
GROUP BY dept
HAVING COUNT(*) > 5;         -- filter groups

Remember

WHERE filters rows, HAVING filters groups.

Key terms

Practice this question in Repaso