AdvancedGROUP BY & Aggregation
Product pairs frequently bought together
The query
SQL
SELECT
p1.name AS product_1,
p2.name AS product_2,
COUNT(*) AS times_bought_together
FROM order_items oi1
JOIN order_items oi2
ON oi1.order_id = oi2.order_id
AND oi1.product_id < oi2.product_id -- avoid duplicates and self-pairs
JOIN products p1 ON oi1.product_id = p1.product_id
JOIN products p2 ON oi2.product_id = p2.product_id
GROUP BY p1.product_id, p1.name, p2.product_id, p2.name
ORDER BY times_bought_together DESC
LIMIT 10;Note
“Market basket analysis using self-join on order_items. product_id < prevents (A,B) and (B,A) duplicates.