# 90-Day Churn by First-Order Cohort and Acquisition Channel

*PostgreSQL · read replica · for the VP of Growth · fictional retailer*

## Summary

This analysis measures the share of new customers who place **no second completed order within 90 days** of their first, by first-order month and acquisition channel. The query runs as one CTE pipeline on the read replica, scans orders once with an index-friendly filter, and only reports cohorts with a full 90-day window. All results depend on your data — [validate] against the reconciliation checks below before sharing.

## Definitions and grain

| Term | Definition |
| --- | --- |
| Completed order | `orders.status` not in (`'cancelled'`, `'refunded'`) [validate the status list] |
| First order | Earliest completed `ordered_at` per customer (UTC) |
| Cohort | `date_trunc('month', first_order_at)` in UTC |
| Churned | No completed order where `first_order_at < ordered_at <= first_order_at + interval '90 days'` |
| Eligible cohort | `first_order_at <= now() - interval '90 days'` |
| Grain of output | One row per cohort month × acquisition channel |

## Data quality checks

```sql
-- 1) Orders with no matching customer (should be 0)
SELECT count(*) AS orphan_orders
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id
WHERE c.customer_id IS NULL;

-- 2) Unknown or null acquisition channels
SELECT coalesce(acquisition_channel, '(null)') AS channel, count(*)
FROM customers
GROUP BY 1
ORDER BY 2 DESC;

-- 3) Status values actually present (confirm the exclusion list)
SELECT status, count(*) FROM orders GROUP BY status ORDER BY 2 DESC;

-- 4) Duplicate order ids (should be 0)
SELECT count(*) - count(DISTINCT order_id) AS duplicate_orders FROM orders;
```

## Main analysis

```sql
-- 90-day churn by first-order cohort and channel (UTC throughout).
WITH completed AS (
  -- Filter once; status is low-cardinality so this uses the
  -- (customer_id, ordered_at) index and a filter, not a separate scan.
  SELECT customer_id, ordered_at
  FROM orders
  WHERE status NOT IN ('cancelled', 'refunded')
),
first_orders AS (
  SELECT customer_id, min(ordered_at) AS first_order_at
  FROM completed
  GROUP BY customer_id
),
eligible AS (
  -- Only customers whose 90-day window has fully elapsed.
  SELECT f.customer_id,
         f.first_order_at,
         date_trunc('month', f.first_order_at AT TIME ZONE 'UTC') AS cohort_month,
         coalesce(c.acquisition_channel, 'unknown') AS channel
  FROM first_orders f
  JOIN customers c USING (customer_id)
  WHERE f.first_order_at <= now() - interval '90 days'
),
repeaters AS (
  -- EXISTS-style semi-join: stops at the first qualifying repeat order.
  SELECT e.customer_id
  FROM eligible e
  WHERE EXISTS (
    SELECT 1
    FROM completed o
    WHERE o.customer_id = e.customer_id
      AND o.ordered_at >  e.first_order_at
      AND o.ordered_at <= e.first_order_at + interval '90 days'
  )
)
SELECT
  e.cohort_month::date                                   AS cohort_month,
  e.channel,
  count(*)                                               AS new_customers,
  count(*) - count(r.customer_id)                        AS churned_customers,
  round(100.0 * (count(*) - count(r.customer_id)) / count(*), 1) AS churn_rate_pct
FROM eligible e
LEFT JOIN repeaters r USING (customer_id)
GROUP BY 1, 2
HAVING count(*) >= 50          -- suppress tiny groups (noise and privacy)
ORDER BY 1, 2;
```

**Performance notes**

- Needs an index on `orders (customer_id, ordered_at)`; check with `EXPLAIN (ANALYZE, BUFFERS)` on the replica. A partial index `WHERE status NOT IN ('cancelled','refunded')` helps further if it is allowed.
- `EXISTS` avoids counting every repeat order; it stops at the first match.
- If the plan still exceeds 30 seconds on 40M orders, materialise `first_orders` as a nightly table [validate runtime].

## Validation

```sql
-- A) New customers in the output must equal eligible customers overall.
SELECT count(*) FROM first_orders WHERE first_order_at <= now() - interval '90 days';
-- compare with: SELECT sum(new_customers) FROM (<main query without HAVING>) q;

-- B) Spot-check one customer by hand.
SELECT customer_id, ordered_at, status
FROM orders
WHERE customer_id = :sample_customer_id   -- pick one churned and one repeater
ORDER BY ordered_at;
```

**Edge cases handled:** same-timestamp duplicate first orders (the repeat must be strictly later); null channels (`unknown`); refunds after a repeat order (refunded orders never count as repeats); cohorts younger than 90 days (excluded).

## Output spec for the VP of Growth

| Element | Spec |
| --- | --- |
| Main view | Heatmap: rows = cohort month, columns = channel, cell = churn rate %; darker = higher churn |
| Companion | Line chart of churn rate % by cohort month, one line per top-4 channel |
| Labels | Show `new_customers` on hover; hide cells with fewer than 50 customers |
| Headline | "[Channel] cohorts churn [x] points more than [channel] over the last [n] months" — fill only from validated results |

## Interpretation template (fill after validation)

- **Overall:** 90-day churn across eligible cohorts is [x]% [validate].
- **Channels:** [channel] has the highest churn at [x]%, [y] points above the average.
- **Trend:** churn has [risen / fallen / stayed flat] over the last [n] cohorts.
- **Caveats:** churn here means "no second order in 90 days", not account closure; seasonality affects December and January cohorts; channel attribution is first-touch only.

## Risks and next steps

- **Risk:** status values may differ by region — confirm with check 3 before sharing.
- **Next:** churn by first-order value band; time-to-second-order distribution; a dbt model with uniqueness and not-null tests on `customer_id`.

**Next steps I can help with:** I can write the dashboard spec or a scheduled dbt version. Can you share the row count from validation A so we can confirm the totals reconcile?
