Skip to content

Funnels

Count how many users reach each step in order, such as view, cart and purchase, and compute step-to-step conversion.

Practise: 8 questions

When you need it

"What share of users who viewed an item added it to the cart, then bought?", "where do people drop off in checkout", "conversion from signup to first purchase". Words that signal it: "funnel", "drop-off", "step", "then", "after", "conversion", "reached".

A funnel is an ordered list of steps. Each user is counted at a step only if they did that step, usually after the one before it.

The shape of the query

with first_times as (
  select user_id,
         min(case when event_name = 'view_item'  then occurred_at end) as viewed_at,
         min(case when event_name = 'add_to_cart' then occurred_at end) as carted_at,
         min(case when event_name = 'purchase'   then occurred_at end) as bought_at
  from events
  group by user_id
)
select count(viewed_at) as viewed,
       count(*) filter (where carted_at >= viewed_at) as carted,
       count(*) filter (where bought_at >= carted_at and carted_at >= viewed_at) as bought
from first_times;

Step by step:

  1. Reduce events to one row per user with the first time of each step. MIN(CASE ...) returns NULL when the user never did it.
  2. Count users at each step. A step counts only if the earlier steps happened and in the right order.
  3. Make each step a subset of the previous one, so counts can only fall.
  4. Divide by the previous step (step conversion) or by the first step (overall conversion).
with first_times as (
  select user_id,
         min(case when event_name = 'view_item'      then occurred_at end) as viewed_at,
         min(case when event_name = 'add_to_cart'    then occurred_at end) as carted_at,
         min(case when event_name = 'begin_checkout' then occurred_at end) as checkout_at,
         min(case when event_name = 'purchase'       then occurred_at end) as bought_at
  from events
  group by user_id
), reached as (
  select user_id,
         viewed_at is not null as s1,
         viewed_at is not null and carted_at >= viewed_at as s2,
         viewed_at is not null and carted_at >= viewed_at and checkout_at >= carted_at as s3,
         viewed_at is not null and carted_at >= viewed_at and checkout_at >= carted_at and bought_at >= checkout_at as s4
  from first_times
)
select count(*) filter (where s1) as viewed,
       count(*) filter (where s2) as carted,
       count(*) filter (where s3) as checkout,
       count(*) filter (where s4) as purchased,
       round(100.0 * count(*) filter (where s4) / nullif(count(*) filter (where s1), 0), 1) as overall_pct
from reached;

Traps interviewers look for

Variations

In other warehouses

Practise funnels