Paid orders per customer, including zero
Task
List every customer with the number of their orders whose status is 'paid'. Customers with no paid orders must appear with 0. Columns: name, paid_orders.
Row order does not matter. Column names do not have to match. SQLite dialect.
Tables
customers
id INTEGER, name TEXT
| id | name |
|---|---|
| 1 | Asha |
| 2 | Ben |
| 3 | Chen |
orders
id INTEGER, customer_id INTEGER, status TEXT
| id | customer_id | status |
|---|---|---|
| 10 | 1 | paid |
| 11 | 1 | paid |
| 12 | 1 | refunded |
| 13 | 2 | refunded |
- A condition on the right-hand table in WHERE turns a LEFT JOIN into an INNER JOIN.
- Move the status filter into the ON clause, and count a column from orders, not *.
Expected output
| name | paid_orders |
|---|---|
| Asha | 2 |
| Ben | 0 |
| Chen | 0 |
Show solution
SQL
SELECT c.name, COUNT(o.id) AS paid_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'
GROUP BY c.id, c.name;Filtering o.status in WHERE drops customers whose order columns are NULL. In the ON clause it only limits which orders match. COUNT(*) would count the NULL-extended row as 1, so count o.id.
Why this works
Filtering o.status in WHERE drops customers whose order columns are NULL. In the ON clause it only limits which orders match. COUNT(*) would count the NULL-extended row as 1, so count o.id.