WHERE vs HAVING in SQL: the difference with examples
Short answer
WHERE filters individual rows before they are grouped. HAVING filters groups after GROUP BY, so it can use aggregate functions such as COUNT, SUM and AVG. You can use both in one query.
The difference at a glance
| WHERE | HAVING | |
|---|---|---|
| Filters | Rows | Groups |
| Runs | Before GROUP BY | After GROUP BY |
| Can use COUNT, SUM, AVG | No | Yes |
| Works without GROUP BY | Yes | Rarely useful |
| Speed | Faster — fewer rows to group | Runs on grouped results |
Example: using both
Show cities with more than 50 orders in 2026:
SELECT city, COUNT(*) AS orders
FROM orders
WHERE order_date >= '2026-01-01' -- rows: only 2026
GROUP BY city
HAVING COUNT(*) > 50; -- groups: only busy cities
The common mistake
-- Error: aggregate in WHERE
SELECT city FROM orders WHERE COUNT(*) > 50 GROUP BY city;
WHERE runs before rows are grouped, so COUNT has nothing to count yet. Move the condition to HAVING.
Interview tip
If a condition does not need an aggregate, put it in WHERE even when the query has GROUP BY. Filtering early means less data to group, which is faster.
Try it yourself
5 questions from the LogicByte practice bank. Pick an answer to check it.
-
1Which query returns all rows where status is 'Active'?
SELECT * FROM Users WHERE status = 'Active';Show answer
Answer: D — SELECT * FROM Users WHERE status = 'Active';
WHERE filters rows based on a condition.