TECHNOLOGIESTieInn Technologies

GROUP BY and HAVING

SQL · 17 questions

Short notes

Key idea

GROUP BY splits rows into groups and runs the aggregates once per group. HAVING filters groups after they are formed; WHERE filters rows before.

Syntax

SELECT city, COUNT(*) AS orders, SUM(amount) AS revenue
FROM orders
WHERE status = 'delivered'
GROUP BY city
HAVING SUM(amount) > 50000
ORDER BY revenue DESC;

Order of running: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.

Example

Customers with more than 3 orders:

SELECT customer_id, COUNT(*) AS n
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 3;

Traps

  • Every plain column in SELECT must be in GROUP BY.
  • Aggregates can't go in WHERE. WHERE COUNT(*) > 3 is an error; use HAVING.
  • Filter in WHERE when you can. It's faster and clearer than HAVING on a non-aggregate.
  • NULLs form one group of their own.

Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    GROUP BY and HAVING

  1. Question 1easy

    You want only cities with more than 3 customers. Where does COUNT(*) > 3 go?

  2. GROUP BY and HAVING

  3. Question 2medium

    Why does this fail? SELECT city, first_name, COUNT(*) FROM customers GROUP BY city

  4. GROUP BY and HAVING

  5. Question 3medium

    Customers live in 9 cities, and 3 have no city. How many rows does the inner query return?

    SELECT COUNT(*) FROM (
      SELECT city, COUNT(*) FROM customers GROUP BY city
    );
  6. GROUP BY and HAVING

  7. Question 4medium

    How many statuses have more than 10 orders?

    SELECT COUNT(*) FROM (
      SELECT status FROM orders
      GROUP BY status
      HAVING COUNT(*) > 10
    );
  8. GROUP BY and HAVING

  9. Question 5hard

    SELECT customer_id, SUM(amount) AS spent FROM orders GROUP BY customer_id HAVING spent > 30000; works in DuckDB. What happens in PostgreSQL?

12 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.