🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

SQL Analytics: Cohorts, Funnels, and Retention

Advanced SQLAnalyticsđŸŸĸ Free Lesson
Advanced SQL

SQL Analytics: Cohorts, Funnels, and Retention

The difference between a report and an analysis is a question. These recipes turn raw event and order tables into answers about acquisition, engagement, and revenue over time.

  • Cohort matrices — group customers by first activity, then measure behavior by age
  • Funnels — stage-by-stage conversion with strict and flexible definitions
  • Retention curves — cohort survival in the shape executives actually read
  • Analyst utilities — percentiles, rolling metrics, deduplication, and date spines Every recipe here is production SQL you can adapt, not pseudocode.

Prerequisites

  • !Window functions: ROW_NUMBER, LAG, and aggregate OVER
  • !CTEs and multi-step query composition
  • !Comfort with date functions in your engine (examples use PostgreSQL)

What You'll Learn

  • 1Define cohort, funnel, and retention metrics precisely enough to defend them
  • 2Build a cohort-by-age retention matrix with window functions and aggregation
  • 3Compute funnel conversion with both strict ordering and flexible stage matching
  • 4Apply percentiles, rolling windows, and deduplication patterns to real datasets

Define the Metric Before Writing the Query

Analytics bugs are rarely syntax bugs. They are definition bugs that survived review because the SQL looked plausible. Before touching the keyboard, pin down four things: the population (who is in the cohort), the event (what counts as an action), the window (how long after cohorting we observe), and the unit (customer, account, session, or dollar). Write the definition in one sentence in the query comments. If you cannot write that sentence, the query cannot be right.

A cohort is a group of entities that share an initial event in the same period — typically the first purchase or signup month. Retention is the fraction of that cohort still active at a later age, where "active" must be defined (any order? order above a minimum? any session?). Funnels track a sequence of stages; they differ from retention in that they measure progression through steps, not survival over calendar time.

MetricQuestion it answersGrain of the output
Cohort matrixHow does each acquisition month behave as it ages?One row per cohort month, one column per age
Retention curveWhat fraction of a cohort survives at age n?Cohort × age rates, often averaged
Funnel conversionHow many proceed from stage to stage?One row per stage, with counts and rates
Rolling revenueWhat is the smoothed trend?Time series with moving aggregates
Percentile bandsWhere does a value sit relative to peers?Buckets or thresholds per segment

Building a Cohort Retention Matrix

The pattern has three moves: compute each customer's first activity month, compute every later activity month, then measure whether each cohort-age pair has activity.

-- Monthly order cohorts with age-based retention
WITH first_order AS (
    SELECT
        customer_id,
        DATE_TRUNC('month', MIN(order_date)) AS cohort_month
    FROM orders
    WHERE status <> 'cancelled'
    GROUP BY customer_id
),
activity AS (
    SELECT DISTINCT
        o.customer_id,
        DATE_TRUNC('month', o.order_date) AS activity_month
    FROM orders o
    WHERE o.status <> 'cancelled'
),
cohort_ages AS (
    SELECT
        f.customer_id,
        f.cohort_month,
        a.activity_month,
        FLOOR(EXTRACT(EPOCH FROM (a.activity_month - f.cohort_month)) / 2592000) AS age_months
    FROM first_order f
    INNER JOIN activity a ON a.customer_id = f.customer_id
    WHERE a.activity_month >= f.cohort_month
)
SELECT
    cohort_month,
    COUNT(DISTINCT CASE WHEN age_months = 0 THEN customer_id END) AS cohort_size,
    ROUND(100.0 * COUNT(DISTINCT CASE WHEN age_months = 1 THEN customer_id END)
        / NULLIF(COUNT(DISTINCT CASE WHEN age_months = 0 THEN customer_id END), 0), 1) AS m1_pct,
    ROUND(100.0 * COUNT(DISTINCT CASE WHEN age_months = 2 THEN customer_id END)
        / NULLIF(COUNT(DISTINCT CASE WHEN age_months = 0 THEN customer_id END), 0), 1) AS m2_pct,
    ROUND(100.0 * COUNT(DISTINCT CASE WHEN age_months = 3 THEN customer_id END)
        / NULLIF(COUNT(DISTINCT CASE WHEN age_months = 0 THEN customer_id END), 0), 1) AS m3_pct
FROM cohort_ages
GROUP BY cohort_month
ORDER BY cohort_month;

For many age columns, pivot the aggregation with FILTER or CASE per age, or aggregate once to a long table (cohort_month, age_months, customers) and pivot in the presentation layer — a stable long shape scales better than hard-coding twenty column expressions. Watch the age arithmetic: month subtraction by epoch seconds assumes 30-day months; for calendar-accurate ages, compute EXTRACT(YEAR FROM AGE(...)) * 12 + EXTRACT(MONTH FROM AGE(...)).

Funnel Conversion, Two Ways

A strict funnel requires the stages to occur in order for the same entity, often within a time limit. A flexible funnel only requires that the entity eventually did each stage, ignoring order. The distinction changes numbers materially, so say which one the dashboard uses.

-- Strict signup-to-paid funnel within 30 days of signup
WITH signup AS (
    SELECT user_id, MIN(event_at) AS signup_at
    FROM events
    WHERE event_name = 'signup_completed'
    GROUP BY user_id
),
activated AS (
    SELECT e.user_id, MIN(e.event_at) AS activated_at
    FROM events e
    INNER JOIN signup s ON s.user_id = e.user_id
    WHERE e.event_name = 'project_created'
      AND e.event_at BETWEEN s.signup_at AND s.signup_at + INTERVAL '30 days'
    GROUP BY e.user_id
),
paid AS (
    SELECT e.user_id, MIN(e.event_at) AS paid_at
    FROM events e
    INNER JOIN signup s ON s.user_id = e.user_id
    WHERE e.event_name = 'subscription_started'
      AND e.event_at BETWEEN s.signup_at AND s.signup_at + INTERVAL '30 days'
    GROUP BY e.user_id
),
staged AS (
    SELECT
        s.user_id,
        1 AS did_signup,
        CASE WHEN a.user_id IS NOT NULL THEN 1 ELSE 0 END AS did_activate,
        CASE WHEN p.user_id IS NOT NULL THEN 1 ELSE 0 END AS did_pay
    FROM signup s
    LEFT JOIN activated a ON a.user_id = s.user_id
    LEFT JOIN paid p ON p.user_id = s.user_id
)
SELECT
    COUNT(*) AS signups,
    SUM(did_activate) AS activated,
    SUM(did_pay) AS paid,
    ROUND(100.0 * SUM(did_activate) / NULLIF(COUNT(*), 0), 1) AS activation_pct,
    ROUND(100.0 * SUM(did_pay) / NULLIF(SUM(did_activate), 0), 1) AS pay_after_activate_pct,
    ROUND(100.0 * SUM(did_pay) / NULLIF(COUNT(*), 0), 1) AS end_to_end_pct
FROM staged;

When events are plentiful, the strict funnel can also be computed in one pass with window functions: MIN(event_at) FILTER per stage, or a state-machine pattern using MAX(stage) OVER (PARTITION BY user_id ORDER BY event_at) to track how far each user progressed before dropping out.

Percentiles, Rolling Metrics, and Deduplication

Three utilities cover a surprising share of ad-hoc analysis.

Percentiles. PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY latency_ms) interpolates (continuous median); PERCENTILE_DISC returns an actual observed value. Use continuous for smooth thresholds, discrete when the threshold must be a real sample — for SLA definitions, discrete is usually correct.

Rolling metrics. Bounded frames give moving aggregates; LAG gives period-over-period comparisons.

-- Rolling 7-day revenue and month-over-month growth from daily totals
WITH daily AS (
    SELECT
        DATE_TRUNC('day', order_date) AS d,
        SUM(total) AS revenue
    FROM orders
    WHERE status = 'paid'
    GROUP BY DATE_TRUNC('day', order_date)
),
enriched AS (
    SELECT
        d,
        revenue,
        AVG(revenue) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rev_7d_avg,
        SUM(revenue) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rev_7d_sum,
        revenue - LAG(revenue, 1) OVER (ORDER BY d) AS dod_change,
        SUM(revenue) OVER (ORDER BY DATE_TRUNC('month', d)) AS month_to_date
    FROM daily
)
SELECT
    d,
    ROUND(revenue, 2) AS revenue,
    ROUND(rev_7d_avg, 2) AS rev_7d_avg,
    ROUND(rev_7d_sum, 2) AS rev_7d_sum,
    ROUND(dod_change, 2) AS dod_change,
    ROUND(month_to_date, 2) AS month_to_date
FROM enriched
ORDER BY d;

Deduplication. Event tables accumulate duplicates and late updates. The standard move is ROW_NUMBER() ordered by ingestion time descending, then keep row 1 per business key. Pair it with a freshness check — MAX(loaded_at) per source — so silent pipeline stalls do not masquerade as business declines.

A date spine completes the toolkit: generate the full calendar (via GENERATE_SERIES in PostgreSQL) and LEFT JOIN your metrics onto it so zero-activity days appear as zeros instead of vanishing. Gaps in a time series are data, not empty space.

Building a Date Spine and Surfacing Zero Days

The date spine deserves its own recipe because nearly every executive dashboard needs it. Generate the calendar range you care about, then attach metrics. Days with no orders must appear with a zero, not disappear — a missing Wednesday between two strong Tuesdays makes the chart lie about continuity, and a user cannot distinguish "no sales" from "ETL failed" without the explicit zero.

-- Date spine with metrics, including explicit zero-revenue days
WITH calendar AS (
    SELECT generate_series(
        DATE '2024-01-01',
        DATE '2024-03-31',
        INTERVAL '1 day'
    )::date AS d
),
daily AS (
    SELECT
        order_date::date AS d,
        SUM(total) AS revenue,
        COUNT(DISTINCT customer_id) AS buyers
    FROM orders
    WHERE status = 'paid'
      AND order_date::date BETWEEN DATE '2024-01-01' AND DATE '2024-03-31'
    GROUP BY order_date::date
)
SELECT
    c.d,
    COALESCE(daily.revenue, 0) AS revenue,
    COALESCE(daily.buyers, 0) AS buyers,
    CASE WHEN daily.d IS NULL THEN TRUE ELSE FALSE END AS is_gap_day
FROM calendar c
LEFT JOIN daily ON daily.d = c.d
ORDER BY c.d;

The is_gap_day flag is not decoration: it lets downstream alerting distinguish a genuinely empty calendar day from a missing feed, which look identical if you only chart the revenue line. The same pattern extends to hourly spines for operational dashboards; just generate the series with the right step and keep the same LEFT JOIN discipline.

Time Zones, Late Arrivals, and Other Traps

Analytics SQL runs on clocks you do not fully control. Three traps account for a large share of bad metrics.

Time zone drift. If order_date is stored as UTC with timezone (the right default) but the business defines a "day" in local time, DATE_TRUNC('day', order_date) buckets by UTC and shifts evening activity into the next day. Convert explicitly before truncating: DATE_TRUNC('day', order_date AT TIME ZONE 'America/New_York'). Pick one reporting time zone per metric and document it in the query header; mixing conventions across dashboards is worse than a slightly wrong but consistent choice.

Late-arriving facts. An order refunded or inserted two days late changes yesterday's numbers. Decide whether reports are point-in-time snapshots (immutable once published) or restated (updated when late data lands), and label which one each dashboard is. Restating dashboards need a watermark so late rows re-open the affected periods; snapshot dashboards need an audit trail explaining why a published figure moved — or did not.

Silent filter drift. A status value renamed upstream (paid becoming settled) drops rows from every query filtering on the old literal. Guard with reconciliation counts against the raw table, and prefer filtering on a conformed status view rather than raw source strings scattered across queries. These traps are invisible in a five-row test dataset; they surface on the first monthly close, which is exactly when trust in the analytics stack is won or lost.

Common Mistakes

Shipping a retention number without a written definition of active

Fix: Comment the population, event, window, and unit in the query header before writing joins

Mixing strict and flexible funnel logic across dashboards

Fix: Standardize one definition per metric and label it in the UI

Using 30-day epoch math for calendar month ages

Fix: Compute age with AGE() or year-month arithmetic to avoid drift across February and DST edges

Letting duplicate events inflate counts

Fix: Deduplicate with ROW_NUMBER over the business key plus ingestion timestamp

Skipping zero days in time series, making trends look smoother than reality

Fix: LEFT JOIN metrics onto a generated date spine

Best Practices

  • Write the metric definition as a comment header in every analytical query
  • Materialize cohort bases as tables or views when reused across dashboards
  • Prefer long-format intermediate results and pivot at the edge for flexible reporting
  • Validate totals: cohort size must equal the sum of retained plus churned at each age
  • Document timezone assumptions — most cohort bugs start with UTC versus local dates

Interview Questions

Q1: How do you compute month-over-month growth in pure SQL?

Aggregate to month grain, then use LAG(value, 1) OVER (ORDER BY month) to fetch the previous month, and compute (value - previous) / NULLIF(previous, 0). Window frames or self-joins give the same result with different trade-offs.

Q2: What is the difference between PERCENTILE_CONT and PERCENTILE_DISC?

PERCENTILE_CONT interpolates between surrounding values and may return a number never observed. PERCENTILE_DISC returns the smallest observed value whose cumulative distribution meets or exceeds the requested percentile — better for SLAs that must reference real samples.

Q3: Why build a date spine for a revenue dashboard?

LEFT JOINing a generated calendar onto daily aggregates surfaces zero-revenue days explicitly. Without the spine, missing days disappear and charts imply continuous activity that did not happen.

Key Takeaways

  • Define population, event, window, and unit before writing analytics SQL
  • Cohort matrices join first-activity month to every later activity month and aggregate by age
  • Strict funnels enforce stage order and time limits; flexible funnels do not — label which you built
  • Rolling windows, LAG comparisons, and percentile functions cover most ad-hoc requests
  • Deduplicate events and fill calendar gaps or your trends will lie quietly
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement