Sobes.tech
Senior

What is the difference between WHERE and HAVING?

sobes.tech AI

Answer from AI

WHERE and HAVING are SQL clauses for filtering data, but they are used at different stages:

  • WHERE filters rows before grouping. It is used to restrict the initial data.
  • HAVING filters groups formed after GROUP BY. It allows setting conditions on aggregate functions.

Example:

SELECT author, COUNT(*) as books_count
FROM books
WHERE price > 100
GROUP BY author
HAVING COUNT(*) > 5;

Here, books with a price greater than 100 are selected first (WHERE), then groups by authors are formed, and only those with more than 5 books are selected (HAVING).

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