Lessons › SQL › Chapter 3: Summarising
SQL lesson
HAVING
HAVING filters groups of rows after they've been summarized.
Try this lesson free →Example
Filtering Grouped Retail Results with HAVING
SELECT category, SUM(revenue) AS total_revenue
FROM orders
GROUP BY category
HAVING SUM(revenue) > 200| category | total_revenue |
|---|---|
| Electronics | 449.49 |
| Home | 210.75 |
Step by step
- Run the query without SUM so you can see what the unfiltered values look like.
SELECT category, revenue FROM orders GROUP BY category HAVING SUM(revenue) > 200; - SUM totals the numbers in a column. Works on numeric columns only.
SELECT category, SUM(revenue) FROM orders GROUP BY category HAVING SUM(revenue) > 200; - AS gives the SUM result a friendly column name so the output reads cleanly.
SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category HAVING SUM(revenue) > 200;
Practice
1. Using orders, find customers who placed more than 1 order.
SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id HAVING COUNT(*) > 12. Using orders, find categories whose total revenue is more than 400.
SELECT category, SUM(revenue) FROM orders GROUP BY category HAVING SUM(revenue) > 4003. Using reviews, find products that have more than 1 review.
SELECT product_id, COUNT(*) FROM reviews GROUP BY product_id HAVING COUNT(*) > 14. Using wishlist, find customers with more than 1 item on their wishlist.
SELECT customer_id, COUNT(*) FROM wishlist GROUP BY customer_id HAVING COUNT(*) > 15. Using employees, find departments with more than 1 employee.
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 1Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →