What is the difference between WHERE and HAVING?

SQL Server T-SQL Basic Fresher1–2 Yrs SQL Query 1 min read

Quick Answer

WHERE filters rows before grouping and can't reference aggregates. HAVING filters groups after GROUP BY and aggregation, so it can use COUNT(), SUM(), etc. Put row-level conditions in WHERE (it reduces work earlier); use HAVING only for conditions on aggregated values.

WHERE runs before GROUP BY, so it filters individual rows and can't see aggregate functions. HAVING runs after grouping, so it filters the groups and can use COUNT, SUM and so on. The rule of thumb is: any condition that's about a single row goes in WHERE because it cuts the data down before the expensive grouping; only put a condition in HAVING if it's genuinely about an aggregate, like “groups with more than one row” for finding duplicates.

  • Logical processing order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.
  • Find duplicates: SELECT Email, COUNT(*) FROM Users GROUP BY Email HAVING COUNT(*) > 1.
  • Anti-pattern: a non-aggregate filter in HAVING (e.g. HAVING Country = 'IN') — move it to WHERE so fewer rows get grouped.