HomeMYSQLWhat is the difference between WHERE and HAVING?

What is the difference between WHERE and HAVING?

The difference between WHERE and HAVING in SQL is subtle but important. Let’s break it down clearly:

AspectWHEREHAVING
PurposeFilters rows before any grouping.Filters groups after aggregation (after GROUP BY).
Used WithWorks on individual row conditions.Works on aggregated data (like SUM(), COUNT(), AVG()).
Aggregation FunctionsCannot use aggregation functions like SUM() or COUNT() directly.Can use aggregation functions directly.
Execution OrderApplied before GROUP BY.Applied after GROUP BY.

Example:

Suppose we have a sales table:

idproductamount
1A100
2B200
3A150
4B50

Using WHERE: Filter rows where amount > 100:

SELECT * FROM sales
WHERE amount > 100;

Result:

idproductamount
2B200
3A150

Using HAVING: Find products whose total sales > 200:

SELECT product, SUM(amount) as total_sales
FROM sales
GROUP BY product
HAVING SUM(amount) > 200;

Result:

producttotal_sales
A250

✅ Key takeaway:

  • WHERE → row-level filtering
  • HAVING → group-level filtering

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *