SQL HAVING

Filter groups.

✍️ 3 exercises + code challenge in this lesson

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

Key Takeaways: SQL HAVING

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.

SQL HAVING Code Example

SQL
-- 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;
Free sign-in required · Google login available

SQL HAVING Practice Exercises

Check what you learned in “SQL HAVING”.

/ 3 solved
Fill in the blank

Keep only countries with more than 1 customer.

SELECT Country, COUNT(*) FROM Customers GROUP BY Country  COUNT(*) > 1;
✓ Correct! Not quite. Try again.
Multiple choice

What is the difference between WHERE and HAVING?

✓ Correct! Not quite. Try again.
Code challenge

Select cities (City) that have 2 or more customers, sorted by City.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

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