HAVING — Complete Guide
HAVING — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of MySQL Tutorial on Toolliyo Academy.
On this page
MySQL Tutorial · Lesson 14 of 100
HAVING
Basics → Advanced
Basics · 1 — SQL · ~6 min · MySQL — Queries & Clauses
What is this?
HAVING filters groups after GROUP BY, like WHERE but for aggregated results. Use it when the condition involves COUNT, SUM, or AVG.
Why should you care?
“Show cities with more than 100 active customers” needs HAVING — WHERE cannot see COUNT because grouping has not happened yet.
See it live — copy this example
Run in MySQL Workbench or the mysql CLI.
SELECT city, COUNT(*) AS cnt
FROM customers
GROUP BY city
HAVING cnt >= 2
ORDER BY cnt DESC;
What happened?
- GROUP BY forms city buckets first.
- HAVING drops buckets where cnt < 2.
- Cities with one lonely customer disappear from the report.
Practice next
- Skew data: put 3 customers in Mumbai, 1 in Kochi.
- Run query; only Mumbai should show if threshold is 2.
- Change HAVING to cnt >= 3 and watch Mumbai vanish.
- HAVING AVG(...) style: add orders JOIN and HAVING SUM(total_inr) > 1000.
- Combine WHERE city IS NOT NULL AND HAVING cnt > 1.
Remember
WHERE filters rows; HAVING filters groups. HAVING can reference aggregate aliases in MySQL. Use for threshold reports on summaries.
Flipkart seller tier report
Only sellers with 50+ SKUs in stock appear in a premium listing — HAVING COUNT(sku) >= 50.
Outcome: List stays high quality without manual spreadsheets.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!