Medium JOINsAggregation Premium

SQL interview question: Products Frequently Bought Together

Frequently Bought Together

The recommendation engine needs to find product pairs frequently purchased in the same order.

Find all product pairs that were purchased together in the same order at least twice.

Return product_1, product_2 (product names), and times_bought_together. Self-join order_items on order_id.

Skills: self-join with aggregation

Tables

order_items 19 rows
  • id integer PK
  • order_id integer → orders
  • product_id integer → products
  • quantity integer
idorder_idproduct_idquantity
1131
2211
3261
products 20 rows
  • product_id integer PK
  • product_name text
  • category text
  • price real
  • rating real
product_idproduct_namecategorypricerating
1MacBook ProElectronics1999.994.8
2iPad AirElectronics599.994.8
3AirPods ProElectronics249.994.7

Keep going