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
SELECTmust be inGROUP BY. - Aggregates can't go in
WHERE.WHERE COUNT(*) > 3is an error; useHAVING. - Filter in
WHEREwhen you can. It's faster and clearer thanHAVINGon 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 →
- Question 1easy
You want only cities with more than 3 customers. Where does
COUNT(*) > 3go? - Question 2medium
Why does this fail?
SELECT city, first_name, COUNT(*) FROM customers GROUP BY city - 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 );
- Question 4medium
How many statuses have more than 10 orders?
SELECT COUNT(*) FROM ( SELECT status FROM orders GROUP BY status HAVING COUNT(*) > 10 );
- 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?
GROUP BY and HAVING
GROUP BY and HAVING
GROUP BY and HAVING
GROUP BY and HAVING
GROUP BY and HAVING
12 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.