Find Product Pairs Most Often Bought Together in One Order
Last updated: November 29, 2026
Quick Overview
Given an order_items table, find the 10 product pairs that appear together in the most orders, and report each pair's lift so that pairs of merely popular products do not dominate.
Amazon
November 29, 20260
0
0 solved
Given an order_items table, find the 10 product pairs that appear together in the most orders, and report each pair's lift so that pairs of merely popular products do not dominate.
Frequently bought together recommendations are a classic Amazon feature, and the underlying SQL is a common screen for Data Scientists and BI engineers. The interviewer checks self-join technique, deduplication, avoiding double counting of symmetric pairs, and understanding of support versus lift.
What the Interviewer Expects
- Deduplicate products within an order before pairing
- Self-join with a.product_id < b.product_id to avoid duplicates and self-pairs
- Count distinct orders per pair
- Compute per-product order counts and lift
- Discuss performance on very large orders
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you restrict to pairs with at least 100 co-occurrences?
- How would you handle orders with hundreds of items that explode the join?
- How would you compute this per category?
- Why might lift favor rare products, and how do you correct it?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
Table order_items(order_id, product_id, quantity). One order can list the same product on multiple rows (for example different sellers or gift options), so we deduplicate. A pair (A, B) is unordered...
Approach
basket: distinct(order_id, product_id).pairs: self-join onorder_idwitha.product_id < b.product_id, counted per pair.prod: orders per product.tot: total distinct orders. 4...