SQL Practice Problem #009

Filter grouped results with HAVING

Find customer_id values that have placed at least two orders.

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

idcustomer_idtotal_amountordered_at
101158.52026-03-02
1021442026-03-05
10321042026-03-07

Output

Expected Output

customer_idorder_count
12

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

Related Problems