The difference between WHERE and HAVING in SQL is subtle but important. Let’s break it down clearly:
| Aspect | WHERE | HAVING |
|---|---|---|
| Purpose | Filters rows before any grouping. | Filters groups after aggregation (after GROUP BY). |
| Used With | Works on individual row conditions. | Works on aggregated data (like SUM(), COUNT(), AVG()). |
| Aggregation Functions | Cannot use aggregation functions like SUM() or COUNT() directly. | Can use aggregation functions directly. |
| Execution Order | Applied before GROUP BY. | Applied after GROUP BY. |
Example:
Suppose we have a sales table:
| id | product | amount |
|---|---|---|
| 1 | A | 100 |
| 2 | B | 200 |
| 3 | A | 150 |
| 4 | B | 50 |
Using WHERE: Filter rows where amount > 100:
SELECT * FROM sales
WHERE amount > 100;
Result:
| id | product | amount |
|---|---|---|
| 2 | B | 200 |
| 3 | A | 150 |
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:
| product | total_sales |
|---|---|
| A | 250 |
✅ Key takeaway:
WHERE→ row-level filteringHAVING→ group-level filtering
