Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 08 / Topic 6 of 10

Funnels

The events table records the funnel steps in order: view, then cart, then purchase. A funnel counts who reached each step — conditional aggregates over one pass:

SELECT count(DISTINCT customer_id) FILTER (WHERE event_type = 'view')     AS viewed,
       count(DISTINCT customer_id) FILTER (WHERE event_type = 'cart')     AS carted,
       count(DISTINCT customer_id) FILTER (WHERE event_type = 'purchase') AS purchased
FROM events;
 viewed | carted | purchased 
--------+--------+-----------
      3 |      2 |         2
(1 row)

Conversion between steps is division — carted/viewed, purchased/carted:

WITH steps AS (
  SELECT count(DISTINCT customer_id) FILTER (WHERE event_type = 'view')     AS viewed,
         count(DISTINCT customer_id) FILTER (WHERE event_type = 'cart')     AS carted,
         count(DISTINCT customer_id) FILTER (WHERE event_type = 'purchase') AS purchased
  FROM events
)
SELECT viewed, carted, purchased,
       round(100.0 * carted / NULLIF(viewed, 0), 0)    AS view_to_cart_pct,
       round(100.0 * purchased / NULLIF(carted, 0), 0) AS cart_to_purchase_pct
FROM steps;
 viewed | carted | purchased | view_to_cart_pct | cart_to_purchase_pct 
--------+--------+-----------+------------------+----------------------
      3 |      2 |         2 |               67 |                  100
(1 row)

A stricter funnel requires the steps in order per customer (viewed before carting, carted before buying) — that version joins events to events on customer_id with a timestamp inequality, or uses min(created_at) FILTER (...) per step and compares. Worth knowing it exists; the counting pattern above is what dashboards actually run.

🧪 Quick quiz — answer from memory, then check.

  1. Why DISTINCT inside the funnel counts?
  2. What makes a funnel "strict"?
Show the answers
  1. A customer who viewed five products is still one person at the view step.
  2. Requiring each step to happen after the previous one for the same customer, not merely at any time.

Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.

Search the guide