Joins · Problem 46 of 118

Orders Never Paid

MediumJoinsShop data

Some orders have no row in payments. Return each order status and orders (how many orders of that status have no payment), sorted by status.

Hint 1

LEFT JOIN payments and keep the rows where the payment is NULL.

Reference solution

SELECT o.status, COUNT(*) AS orders
FROM orders AS o
LEFT JOIN payments AS p ON p.order_id = o.order_id
WHERE p.payment_id IS NULL
GROUP BY o.status
ORDER BY o.status;

The result is informative: only cancelled and pending orders have no payment, which is what a healthy business expects. Anti-joins often double as data quality checks: if a delivered order appeared here, something would be wrong. Check for missing rows with payment_id IS NULL (the primary key of the right table), not with a nullable column.