BBampaa

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 →
About 5–10 minutes · no sign-up needed

Example

Keep only some groups

SELECT category, SUM(revenue) AS total_revenue
FROM orders
GROUP BY category
HAVING SUM(revenue) > 200

Result:

categorytotal_revenue
Electronics449.49
Home210.75

Step by step

  1. Keeps only the groups that pass a rule.
    SELECT category, SUM(revenue) AS total_revenue FROM orders GROUP BY category HAVING SUM(revenue) > 200
  2. 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
  3. 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

Try each one in your head first, then open the answer.

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(*) > 1
2. 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) > 400
3. 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(*) > 1
4. 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) > 300
5. 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) > 60000

Learn 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 →
About 5–10 minutes · no sign-up needed