SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 4 / 37

Junior

How does WHERE differ from HAVING?

Short answer

WHERE filters individual rows before grouping, so it cannot use aggregate functions. HAVING filters groups after GROUP BY, so conditions on COUNT, SUM, AVG go there.

TableWHERE: filter rowsno aggregatesGROUP BY: form groupsHAVING: filter groupsCOUNT, SUM, AVGSELECT

3 points to say:

  1. WHERE filters rows before grouping and cannot use aggregates.
  2. HAVING filters groups after GROUP BY; put plain conditions in WHERE to use indexes and filter early.
  3. Every SELECT column must be in GROUP BY or aggregated.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.