Interview Questions/SQL/Market Basket Analysis - Most Frequently Co-Purchased Products

Market Basket Analysis - Most Frequently Co-Purchased Products

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a Purchases table where each row represents one product in one order. Multiple products can appear in the same order. Write a SQL query to find all pairs of products that were purchased together in the same order, and count how many times each pair appeared. Only report pairs where product_1 < product_2 (lexicographic order) to avoid duplicates. Return product_1, product_2, and times_bought_together, ordered by times_bought_together descending, then product_1, then product_2. Table: Purchases

Column NameTypeDescription
order_idINTID of the order
productVARCHARName or ID of the product

Database Schema (Inferred)

Purchases

Column NameExample Value
order_id1
productA

Example

Purchases

order_idproduct
1A
1B
1C
2A
2B
3B
3C
4A
4B
4C
5A
5C

Output

product_1product_2times_bought_together
AB3
AC3
BC3

Explanation:

A+B appear in orders 1,2,4 (3 times). A+C appear in orders 1,4,5 (3 times). B+C appear in orders 1,3,4 (3 times).

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Purchases

order_idproduct
1A
1B
1C
2A
2B
3B
3C
4A
4B
4C
5A
5C

Output

product_1product_2times_bought_together
AB3
AC3
BC3