Customers Who Bought from Every Category
Only some categories have products. Return the customer_id of every customer who has bought (on any non-cancelled order) at least one product from every category that has products. Sort by customer_id.
Hint 1
Count the different categories each customer bought from, and compare with the number of categories that have products.
Reference solution
SELECT o.customer_id
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
JOIN products AS p ON p.product_id = oi.product_id
WHERE o.status <> 'cancelled'
GROUP BY o.customer_id
HAVING COUNT(DISTINCT p.category_id) = (SELECT COUNT(DISTINCT category_id) FROM products)
ORDER BY o.customer_id;
"For all X" questions are called relational division. The standard solution: count the distinct X each entity has, and compare with the total number of X. The trap is the total: here three of the ten categories are parents with no products of their own, so no customer can ever reach 10, and the wrong query returns nothing. Always check that the "all" you compare with is the right set.