IntermediateJoins & NULLs

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

idname
1Asha
2Ben
3Chen

orders

id INTEGER, customer_id INTEGER, status TEXT

idcustomer_idstatus
101paid
111paid
121refunded
132refunded
Expected output
namepaid_orders
Asha2
Ben0
Chen0
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.