Lessons › SQL › Chapter 3: Summarising
SQL lesson
HAVING
HAVING filters groups after GROUP BY has worked out their totals, like keeping categories over 200. WHERE filters rows before grouping. HAVING filters the totals after.
Try this lesson free →Example
Keep only some groups
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
- Keeps only the groups that pass a rule.
SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category HAVING SUM(revenue) > 200 - It goes after GROUP BY and can use SUM or COUNT.
SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category HAVING SUM(revenue) > 200 - WHERE filters rows before grouping. HAVING filters the totals after.
SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category HAVING SUM(revenue) > 200
Practice
1. Using orders, show each customer_id and how many orders they placed, for customers who placed more than 1 order.
SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id HAVING COUNT(*) > 12. Using orders, show each category and its total revenue, for categories whose total revenue is more than 400.
SELECT category, SUM(revenue) FROM orders GROUP BY category HAVING SUM(revenue) > 4003. Using reviews, show each product_id and its number of reviews, for products that have more than 1 review.
SELECT product_id, COUNT(*) FROM reviews GROUP BY product_id HAVING COUNT(*) > 14. Using store_sales, show each store_id and its total revenue, for stores whose total revenue is more than 300.
SELECT store_id, SUM(revenue) FROM store_sales GROUP BY store_id HAVING SUM(revenue) > 3005. Using employees, show each department and its average salary, for departments with an average salary above 60000.
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 60000Learn 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 →