Joins · Problem 52 of 118

Accounts per Customer, Zeros Included

MediumJoinsBank data

For customers 1 to 12, return customer_id and accounts (the number of accounts, 0 if none). Sort by customer_id.

Hint 1

COUNT(*) counts the joined row even when the right side is empty. Count a column of the right-hand table instead.

Reference solution

SELECT c.customer_id, COUNT(a.account_id) AS accounts
FROM customers AS c
LEFT JOIN accounts AS a ON a.customer_id = c.customer_id
WHERE c.customer_id BETWEEN 1 AND 12
GROUP BY c.customer_id
ORDER BY c.customer_id;

After a LEFT JOIN, a customer without accounts still produces one joined row (with NULLs on the right). COUNT(*) counts that row and reports 1; COUNT(a.account_id) counts only non-NULL values and correctly reports 0. Always count a column from the optional side.