Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 76/ 160
04. Subqueries & Common Table Expressions (CTEs)

Funnel Conversion Analysis Queries with CTEs

Measure step-to-step conversion rates through product funnels in SQL.

AdvancedFunnel Steps · Conversion Rate3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Count how many people reach each step, in order, and see what share make it from one step to the next.

Think of it like…

A running race with checkpoints: you count how many runners pass checkpoint 1, then how many of those pass checkpoint 2, and so on. A runner who cut across the field to checkpoint 3 doesn't count for it.

Where you’ve seen it

An e-commerce funnel for November: 10,000 users viewed a product, 2,400 added to cart, 900 started checkout and 610 purchased. Step conversion from checkout to purchase is 610 / 900 ≈ 68%; overall conversion is 6.1%.

Words you’ll hear

Step
A defined event in the funnel, such as add_to_cart.
Step conversion
Users reaching step n ÷ users reaching step n−1.
Ordered funnel
A step counts only if it happened after the previous step.
Conversion window
The maximum time allowed from the first step to the last, such as 7 days.

Visual diagram

Loading interactive diagram

Theory & example queries

One row per user with step timestamps

Start by pivoting events into one row per user with the first time they did each step: MIN(CASE WHEN event = 'view' THEN ts END) AS t_view, and so on. This turns millions of events into a compact table that's easy to reason about.

Then apply the order: a user reaches "cart" only if t_cart > t_view, "checkout" only if they reached cart and t_checkout > t_cart. Count users who satisfy each condition. Taking the first occurrence of each step is a simplification; strict funnels look for the first cart event after the first view, which needs a slightly more careful query.

Ordered funnel (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  u AS (3    SELECT4      user_id,5      MIN(ts) FILTER (6        WHERE7          event = 'view'8      ) AS v,9      MIN(ts) FILTER (10        WHERE11          event = 'cart'12      ) AS c,13      MIN(ts) FILTER (14        WHERE15          event = 'purchase'16      ) AS p17    FROM18      events19    WHERE20      ts >= '2026-11-01'21    GROUP BY22      user_id23  )24SELECT25  COUNT(v) AS viewed,26  COUNT(*) FILTER (27    WHERE28      c > v29  ) AS carted,30  COUNT(*) FILTER (31    WHERE32      c > v33      AND p > c34  ) AS purchased35FROM36  u;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/36
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output1 sample row
Expected output
viewedcartedpurchased
100003200840

Note: Illustrative funnel counts for events since 2026-11-01, with later-step ordering enforced by the timestamp predicates.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Pivot to one row per user with step times, then enforce order when counting.

Windows, segments and common traps

Add a conversion window by requiring the last step within some time of the first (p <= v + interval '7 days'), otherwise a purchase three months later counts as conversion from an old view. Segment the funnel by device, channel or country by adding that column to the per-user table and grouping by it.

Count users, not events: a user who adds ten items to the cart is still one user at that step. Decide how to treat users who skip steps (purchasing via a "buy now" button without a cart), and say whether the funnel is open (users can enter at any step) or closed (they must start at step 1).

Adding a 7-day window

COUNT(*) FILTER (WHERE c > v AND p > c AND p <= v + interval '7 days') AS purchased_7d

Key takeaway: Add a window, count users, and define how skipped steps are treated.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Define the steps and period

List the events in order, the date range of users entering the funnel, and the conversion window.

Focus at this step

view → cart → checkout → purchase, 7 days

What to watch at this step
Decide
open or closed funnel
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A funnel measures how many users complete each step of an ordered process (view product → add to cart → checkout → purchase) and the conversion rate between steps. In SQL you find, per user, when they first did each step, keep only steps done in the right order (and often within a time window), then count users at each step.

Why it matters: Funnels show exactly where users drop out, which is what product and growth teams act on. Funnel queries are a common analytics interview problem, because doing them correctly means counting users rather than events and enforcing the step order.

When to reach for it

  • Checkout and signup conversion analysis
  • Finding the biggest drop-off step
  • Comparing funnels across devices or channels

When to avoid or be careful

  • Counting events instead of distinct users
  • Ignoring step order
  • Running a funnel without a conversion window

Ways to compute a funnel

Per-user step timestamps (MIN + FILTER)
Best for: Most funnels with a handful of steps

Strengths: One pass over events; clear, testable conditions.

Watch out: First-occurrence logic is a simplification for repeated attempts.

Chained LEFT JOINs with time conditions
Best for: Strict "next step after the previous one" logic

Strengths: Precise ordering per attempt.

Watch out: More joins and slower on large event tables.

Analytics tools (Amplitude, Mixpanel, GA)
Best for: Exploring funnels without writing SQL

Strengths: Fast and visual.

Watch out: Definitions are hidden and hard to reconcile with SQL numbers.

Interview signals & numbers to know

When this topic comes up

  • “Where do users drop off?”
  • “Conversion rate from cart to purchase”
  • Signup or checkout funnel
  • Ordered events
  • Growth analytics

Benchmarks & rules of thumb

n ÷ (n−1) -
step conversion
last ÷ first -
overall conversion
1 row -
per user in the pivot step

Common mistakes & follow-ups

Common interview mistakes

  • Counting add_to_cart events and reporting more carts than viewers.
  • Counting a purchase that happened before the user's first view as a conversion.
  • Comparing funnels built with different conversion windows.

Likely interviewer follow-ups

  • How would you enforce that each step happens after the previous one?
  • How would you show the funnel separately for mobile and desktop?
  • How do you handle users who skip a step?
Interview tip: State the definitions first (steps, order, window, open or closed), then pivot to one row per user. It shows you know a funnel's numbers depend entirely on those choices.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Funnel Conversion Analysis Queries with CTEs with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Multi-Step Cohort & Retention Analysis Using CTEs
Next topic
Calculating Running Balances & Period-over-Period Growth