SQL Practice Problem #004

Count orders per customer

Return each customer_id and the number of orders placed by that customer.

Problem

Task

Return each customer_id and the number of orders placed by that customer.

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
21

Answer

Check Your Solution

Show Answer and Explanation

Correct Answer

SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id;

Explanation

GROUP BY creates one group for each customer_id. COUNT(*) then counts how many rows are in each group.

Common Mistakes

  • Selecting id together with customer_id without grouping by id.
  • Using COUNT(customer_id) when the intent is to count all order rows.
  • Forgetting to give the aggregate result a readable alias.

Concepts

Related Concepts

GROUP BY COUNT Aggregate Functions Aggregation

Next practice

Related Problems