How do you keep customers with no paid orders?
Question
Return every customer ID and its paid order count. Keep customers with no orders and customers with only unpaid orders. Sort by customer ID.
customers
| customer_id |
|---|
| 1 |
| 2 |
| 3 |
orders
| order_id | customer_id | status |
|---|---|---|
| 11 | 1 | paid |
| 12 | 1 | void |
| 21 | 2 | pending |
| 13 | 1 | paid |
Show hints (2)
- "KEEP LEFT ROWS"
Start from customers. Where can you put the paid condition so a customer still gets a row when no order matches?
- "COUNT MATCHES ONLY"
Count a right-side column that is present whenever an order matches.
Show checked explanation
Use a LEFT JOIN with the paid test in ON. Count the matching order_id values instead of joined rows.
SELECT c.customer_id, COUNT(o.order_id) AS paid_orders FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.customer_id AND o.status = 'paid' GROUP BY c.customer_id ORDER BY c.customer_id;
customer_id | paid_orders 1 | 2 2 | 0 3 | 0
Ran the query on SQLite 3.49 with the sample rows and edge cases.
Walkthrough
Customer 1 has two paid matches. Customer 2 has an order, but it does not match the paid condition. Customer 3 has no order at all. The left join provides one row with NULL order columns for each of the last two customers. COUNT(o.order_id) ignores those nulls.
Common mistakes
- Putting the paid test in
WHEREremoves the rows for customers 2 and 3. - Counting
*gives each customer with zero paid orders a count of one. - Filtering with
WHERE status = 'paid' OR order_id IS NULLstill drops customers with only unpaid orders.
Follow-up questions
- "How would you keep only customers with at least two paid orders?" Add
HAVING COUNT(o.order_id) >= 2afterGROUP BY. - "What if the order ID can be null on a real match?" Count a right-side column guaranteed to be present on matched rows, such as a non-null primary key.
What a strong answer covers
Explain where the filter belongs and why counting the right-side key yields zero.
Open in interactive practice deck →