← Back to SQL, page 22

sql-0427 · Hard senior

List users who viewed a product, then added it to the cart, then purchased it, in that order.

Join the events table to itself three times on user and product, requiring the view time before the cart time and the cart time before the purchase time. EXISTS-based filters or MIN timestamps per step avoid row multiplication when a user repeats a step.

Full answer
sql
CREATE TABLE events (user_id INTEGER, product TEXT, kind TEXT, ts TEXT);
INSERT INTO events VALUES
 (1, 'Lamp', 'view', '2026-03-01 10:00'), (1, 'Lamp', 'cart', '2026-03-01 10:05'), (1, 'Lamp', 'purchase', '2026-03-01 10:09'),
 (2, 'Lamp', 'cart', '2026-03-02 09:00'), (2, 'Lamp', 'view', '2026-03-02 09:01'), (2, 'Lamp', 'purchase', '2026-03-02 09:03'),
 (3, 'Bag', 'view', '2026-03-03 12:00'), (3, 'Bag', 'view', '2026-03-03 12:01'), (3, 'Bag', 'cart', '2026-03-03 12:02');
sql
SELECT DISTINCT v.user_id, v.product
FROM events v
JOIN events c ON c.user_id = v.user_id AND c.product = v.product AND c.kind = 'cart' AND c.ts > v.ts
JOIN events p ON p.user_id = v.user_id AND p.product = v.product AND p.kind = 'purchase' AND p.ts > c.ts
WHERE v.kind = 'view' ORDER BY v.user_id;
user_idproduct
1Lamp

Only user 1 completed the steps in order. User 2 bought the lamp but added it to the cart before viewing it, so the ordered funnel rejects them, and user 3 never purchased. DISTINCT removes duplicate matches when a step repeats, as user 3's two views would produce if they had gone on to buy. For funnel counts per step, a common pattern computes each user's first timestamp per step with conditional MIN, then compares those timestamps; that scales better than chained self-joins.

sql
CREATE TABLE events (user_id INTEGER, product TEXT, kind TEXT, ts TEXT);
INSERT INTO events VALUES
 (1, 'Lamp', 'view', '2026-03-01 10:00'), (1, 'Lamp', 'cart', '2026-03-01 10:05'), (1, 'Lamp', 'purchase', '2026-03-01 10:09'),
 (2, 'Lamp', 'cart', '2026-03-02 09:00'), (2, 'Lamp', 'view', '2026-03-02 09:01'), (2, 'Lamp', 'purchase', '2026-03-02 09:03'),
 (3, 'Bag', 'view', '2026-03-03 12:00'), (3, 'Bag', 'view', '2026-03-03 12:01'), (3, 'Bag', 'cart', '2026-03-03 12:02');

SELECT DISTINCT v.user_id, v.product
FROM events v
JOIN events c ON c.user_id = v.user_id AND c.product = v.product AND c.kind = 'cart' AND c.ts > v.ts
JOIN events p ON p.user_id = v.user_id AND p.product = v.product AND p.kind = 'purchase' AND p.ts > c.ts
WHERE v.kind = 'view' ORDER BY v.user_id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Chain steps with self-joins and time order
  • Match on user and product
  • DISTINCT handles repeated steps
  • Conditional MIN per step scales better

Common mistakes

  • Ignoring event order
  • Counting duplicate matches from repeated events

Follow-ups

  • How would you count users at each funnel step?
  • How would you require all steps within 30 minutes?

Tips

  • State the ordering rule