WHERE filters rows before grouping; HAVING filters groups after grouping. Use HAVING with aggregate functions.
Clause order: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
Filter groups.
✍️ 3 exercises + code challenge in this lessonWHERE filters rows before grouping; HAVING filters groups after grouping. Use HAVING with aggregate functions.
Clause order: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
Mastering SQL HAVING helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
-- Customers with more than one order
SELECT c.CustomerName, COUNT(o.OrderID) AS Orders
FROM Customers c
JOIN Orders o ON o.CustomerID = c.CustomerID
GROUP BY c.CustomerName
HAVING COUNT(o.OrderID) > 1;
-- Categories whose total stock value is over 1,000,000
SELECT Category, SUM(Price * Stock) AS StockValue
FROM Products
GROUP BY Category
HAVING StockValue > 1000000;
Check what you learned in “SQL HAVING”.
Keep only countries with more than 1 customer.
SELECT Country, COUNT(*) FROM Customers GROUP BY Country COUNT(*) > 1;
What is the difference between WHERE and HAVING?
Select cities (City) that have 2 or more customers, sorted by City.
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services