Difference Between WHERE and HAVING in SQL: A Complete Guide with Examples

Here’s a simple and clear explanation of the difference between WHERE and HAVING in SQL:

Quick Explanation

  • WHERE filters individual rows before any grouping occurs.
  • HAVING filters groups of rows after aggregation (like SUM, COUNT, AVG).
Difference Between WHERE and HAVING in SQL: A Complete Guide with Examples

Difference Between WHERE and HAVING

FeatureWHEREHAVING
PurposeFilters rows before grouping (used on individual rows)Filters groups after grouping (used with GROUP BY)
Used WithAny table or queryOnly with GROUP BY or aggregate functions
AggregatesCannot use aggregate functions like SUM(), COUNT() directlyCan use aggregate functions to filter grouped results
ExecutionApplied first, before groupingApplied after aggregation/grouping
ExampleSELECT * FROM sales WHERE amount > 500;SELECT region, SUM(amount) FROM sales GROUP BY region HAVING SUM(amount) > 5000;

Example

Using WHERE:

sql

SELECT * 
FROM employees
WHERE salary > 50000;

Returns employees with salary > 50,000.

Works on individual rows.

Using HAVING:

sql
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000;

Returns only departments where average salary > 60,000.

Works on grouped results, not individual rows.

Tip to remember:

  • Use WHERE for filtering rows before aggregation.
  • Use HAVING for filtering after aggregation.

Memory Trick

Think of it like a “Filter Timing”:

  • WHERE → “Before Grouping”
    • Filters individual rows before they are grouped.
    • Mnemonic: “Where the row goes” → decides which rows enter the group.
  • HAVING → “After Grouping”
    • Filters groups after aggregation.
    • Mnemonic: “Having the group pass?” → decides which groups stay.

Quick Visual

Data Rows  →  WHERE filters rows  →  GROUP BY  →  HAVING filters groups

Tip: If you are using SUM, COUNT, AVG, think HAVING.
If checking a single column value, think WHERE.