Practice Free
HardJoins High Frequency

Frequently Co-Purchased Product Pairs (Self-Join)

Frequently Asked By:AmazonShopifyUber
Interactive In-Browser Workspace

Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.

Solve in Workbench

Problem Statement

Self-join `order_items` (`p1` and `p2`) on `order_id` where `p1.product_id < p2.product_id` (to avoid duplicates and self-pairings). Group by the pair of products and count how many distinct orders contained both products. Return: 1. `p1.product_id` AS `product_a` 2. `p2.product_id` AS `product_b` 3. `pair_order_count`: Number of shared orders Filter for pairs with `pair_order_count >= 2`. Order results by `pair_order_count` descending, then by `product_a` ascending, then by `product_b` ascending.

Why Technical Interviewers Ask This

Market basket analysis uses self-joins on shopping cart items to uncover item pairs that customers consistently purchase together in the same order.

Common Pitfalls & Interview Traps

Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass joins constructs.

Canonical Modern SQL Solution

PostgreSQL 16 / ANSI SQL
SELECT 
        p1.product_id AS product_a,
        p2.product_id AS product_b,
        COUNT(*) AS pair_order_count
      FROM order_items p1
      JOIN order_items p2 ON p1.order_id = p2.order_id AND p1.product_id < p2.product_id
      GROUP BY p1.product_id, p2.product_id
      HAVING COUNT(*) >= 2
      ORDER BY pair_order_count DESC, product_a ASC, product_b ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Joins. It meets the target criteria: Co-purchased product pairs appearing in at least 2 common orders.

Edge Cases to Verbally Clarify with Your Interviewer

The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.

Frequently Asked Follow-Up Questions

What makes this question a favorite among Amazon and Shopify interviewers?

Interviewers use this problem to test whether candidates write defensive, scalable Joins queries that run efficiently on multi-million row production databases without excessive memory usage.

How does the query optimizer execute this query?

Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.

More FAANG SQL Interview Questions

View all questions