Chapter 9 · Interview Level
35. Market Basket: Frequently Co-Purchased Products
Hard40 XPE-Commerce
Find pairs of products that are frequently bought together in the same order. For each pair, count how many orders contain both products. Only include pairs appearing in at least 2 orders. Show product_a name, product_b name, and co_purchase_count. Avoid duplicate pairs (A,B and B,A): product_a must be the product with the smaller product id. Sort by count descending.
Tables
- PKidINT
- nameTEXT
- FKcategory_id→ categories.idINT
- priceREAL
- costREAL
- stock_quantityINT
- created_atTIMESTAMP
- PKidINT
- FKorder_id→ orders.idINT
- FKproduct_id→ products.idINT
- quantityINT
- unit_priceREAL
- discountREAL
Need help?
Ask Sol
AI tutor — looks at your current query and nudges you, without spoiling the answer.
Solution
Try the hints first — solving it yourself is what makes it stick.