Interview Questions/SQL/Market Basket Item-Chain Frequency

Market Basket Item-Chain Frequency

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

Medium

Description

You are given Orders and OrderItems tables. Using a recursive CTE, generate all item chains (sequences of 2 or 3 items sorted by item_id) that appear together in the same order. Count how many distinct orders contain each chain. Return (chain, chain_length, order_count) ordered by order_count DESC, then chain_length DESC, then chain ASC. Only return chains of length 2 or 3. A chain is a string of item names separated by ' -> ', where items are listed in ascending item_id order. Table: Orders

Column NameTypeDescription
order_idINTPrimary key
customer_idINTCustomer identifier
order_dateDATEDate of order

Table: OrderItems

Column NameTypeDescription
order_idINTReferences Orders
item_idINTItem identifier (used for ordering)
item_nameVARCHARHuman-readable item name

Database Schema (Inferred)

Orders

Column NameExample Value
order_id1
customer_id101
order_date2024-01-01

OrderItems

Column NameExample Value
order_id1
item_id1
item_nameApple

Example

Orders

order_idcustomer_idorder_date
11012024-01-01
21022024-01-02
31032024-01-03
41012024-01-04

OrderItems

order_iditem_iditem_name
11Apple
12Banana
13Cherry
21Apple
23Cherry
32Banana
33Cherry
34Date
41Apple
42Banana
44Date

Output

chainchain_lengthorder_count
Apple -> Banana22
Apple -> Cherry22
Banana -> Cherry22
Banana -> Date22
Apple -> Banana -> Cherry31
Apple -> Banana -> Date31
Banana -> Cherry -> Date31
Apple -> Date21
Cherry -> Date21

Explanation:

Anchor: each item in an order as a chain of length 1. Recursive step: extend chains by joining any item from the same order with a higher item_id, guarding against revisits via chain_ids string. Filter for chain_length > 1 in final aggregation. Count DISTINCT order_id per chain.

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...

Orders

order_idcustomer_idorder_date
11012024-01-01
21022024-01-02
31032024-01-03
41012024-01-04

OrderItems

order_iditem_iditem_name
11Apple
12Banana
13Cherry
21Apple
23Cherry
32Banana
33Cherry
34Date
41Apple
42Banana
44Date

Output

chainchain_lengthorder_count
Apple -> Banana22
Apple -> Cherry22
Banana -> Cherry22
Banana -> Date22
Apple -> Banana -> Cherry31
Apple -> Banana -> Date31
Banana -> Cherry -> Date31
Apple -> Date21
Cherry -> Date21