Skip to content
Discussion options

You must be logged in to vote

Good question!

The main difference is when the filtering happens.

  • WHERE filters rows before grouping
  • HAVING filters groups after GROUP BY

Example:

Table: sales

product amount
Pen 10
Pen 15
Book 50
Book 60

Find products whose total sales > 50:

SELECT product, SUM(amount) AS total
FROM sales
GROUP BY product
HAVING SUM(amount) > 50;

Here, HAVING is used because SUM(amount) is calculated after grouping.

If we used WHERE:
SELECT * FROM sales WHERE amount > 50;

This filters individual rows, not grouped results.

So:

  • Use WHERE for row-level filtering
  • Use HAVING for aggregate filtering

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by suyXcode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
help wanted Extra attention is needed
2 participants