Home / SQL Tutorial / Day 8
Day 8 — HAVING, and how it differs from WHERE
A classic interview question, and a genuine source of wrong reports: WHERE filters rows, HAVING filters groups.
The one-line difference
WHEREruns before grouping — it filters individual rows.HAVINGruns after grouping — it filters the totals.
So you cannot use an aggregate in WHERE, and you would not use HAVING for something a WHERE could do.
HAVING in action
Reps with more than 3 orders. Try changing 3 to 4.
HAVING on a total
Both together — and the order matters
Read this as: keep Delivered orders, group them by rep, then keep only reps whose delivered revenue passes 200000.
The order SQL is written in
SELECT which columns
FROM which table
WHERE filter rows
GROUP BY collapse into groups
HAVING filter the groups
ORDER BY sort the result
LIMIT trim the result
Worth memorising
That is also close to the order the database actually runs them in — which is why an alias created in SELECT cannot be used in WHERE, but usually can be in ORDER BY.
Departments with more than one person
Try these yourself
- Cities with more than one customer.
- Departments whose total salary is above 1000000.
- Statuses that occur more than 3 times in Orders.
- Reps averaging more than 60000 per order.
- Explain in one sentence why COUNT(*) cannot go in WHERE.
Want this taught properly?
This tutorial covers the basics. Our SQL course in Noida takes you through window functions, CTEs and stored procedures on a real database, with projects and mentor support.
See the SQL course →