๐ง SQL Interview Question (Products Frequently Bought Together)
๐
order_items(order_id, product_id)
โ Ques :
๐ Find pairs of products that are frequently bought together in the same order
๐ Return product_id_1, product_id_2, pair_count
๐งฉ How Interviewers Expect You to Think
โข Self-join on same order ๐
โข Avoid duplicate/reverse pairs
โข Count frequency of each pair
๐ก SQL Solution
SELECT
o1.product_id AS product_id_1,
o2.product_id AS product_id_2,
COUNT(*) AS pair_count
FROM order_items o1
JOIN order_items o2
ON o1.order_id = o2.order_id
AND o1.product_id < o2.product_id
GROUP BY
o1.product_id,
o2.product_id
ORDER BY pair_count DESC;
๐ฅ Why This Question Is Powerful
โข Classic market basket analysis ๐ง
โข Tests self-join + combinations logic
โข Frequently asked in e-commerce & analytics roles
โค๏ธ React for more SQL interview questions ๐
Post #2128
2.72K
- โค 7