BBampaa

Lessons › SQL › Chapter 3: Summarising

SQL lesson

HAVING

HAVING filters groups of rows after they've been summarized.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Filtering Grouped Retail Results with HAVING

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. 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;
  2. 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;
  3. 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

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

1. Using orders, find customers who placed more than 1 order.
SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id HAVING COUNT(*) > 1
2. Using orders, find categories whose total revenue is more than 400.
SELECT category, SUM(revenue) FROM orders GROUP BY category HAVING SUM(revenue) > 400
3. Using reviews, find products that have more than 1 review.
SELECT product_id, COUNT(*) FROM reviews GROUP BY product_id HAVING COUNT(*) > 1
4. Using wishlist, find customers with more than 1 item on their wishlist.
SELECT customer_id, COUNT(*) FROM wishlist GROUP BY customer_id HAVING COUNT(*) > 1
5. Using employees, find departments with more than 1 employee.
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 1

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