Problem
Task
Find customer_id values that have placed at least two orders.
Schema
Table Schema
orders(id, customer_id, total_amount, ordered_at)
Input
Sample Data
| id | customer_id | total_amount | ordered_at |
|---|---|---|---|
| 101 | 1 | 58.5 | 2026-03-02 |
| 102 | 1 | 44 | 2026-03-05 |
| 103 | 2 | 104 | 2026-03-07 |
Output
Expected Output
| customer_id | order_count |
|---|---|
| 1 | 2 |
Answer
Check Your Solution
Show Answer and Explanation
Correct Answer
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 2;
Explanation
WHERE filters rows before grouping, while HAVING filters groups after aggregation. Because the condition depends on COUNT(*), it belongs in HAVING.
Common Mistakes
- Putting COUNT(*) >= 2 inside WHERE.
- Grouping by id instead of customer_id.
- Using HAVING before GROUP BY.
Concepts
Related Concepts
HAVING
GROUP BY
Aggregate Filtering
COUNT
Next practice