Difference between WHERE and HAVING in SQL with example? #5
-
|
Hi everyone 👋 I understand that both WHERE and HAVING are used to filter data, but I’m confused about when exactly to use each one. Can someone explain the difference between WHERE and HAVING with a simple real-world example? Thanks in advance 🙂 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Good question! The main difference is when the filtering happens.
Example: Table: sales
Find products whose total sales > 50: SELECT product, SUM(amount) AS total Here, If we used This filters individual rows, not grouped results. So:
|
Beta Was this translation helpful? Give feedback.
Good question!
The main difference is when the filtering happens.
WHEREfilters rows before groupingHAVINGfilters groups after GROUP BYExample:
Table: sales
Find products whose total sales > 50:
SELECT product, SUM(amount) AS total
FROM sales
GROUP BY product
HAVING SUM(amount) > 50;
Here,
HAVINGis used becauseSUM(amount)is calculated after grouping.If we used
WHERE:SELECT * FROM sales WHERE amount > 50;
This filters individual rows, not grouped results.
So:
WHEREfor row-level filteringHAVINGfor aggregate filtering