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

Part 08 / Topic 5 of 10

Cohort retention

Group customers by when they started (their cohort), then ask how many came back later: take each customer's first-order month, and ask whether they ordered again in any later month.

WITH first_orders AS (
  SELECT customer_id,
         date_trunc('month', min(order_date))::date AS cohort_month
  FROM orders
  GROUP BY customer_id
),
activity AS (
  SELECT DISTINCT o.customer_id,
         date_trunc('month', o.order_date)::date AS active_month
  FROM orders AS o
)
SELECT f.cohort_month,
       count(DISTINCT f.customer_id) AS cohort_size,
       count(DISTINCT a.customer_id)
         FILTER (WHERE a.active_month > f.cohort_month) AS returned_later
FROM first_orders AS f
LEFT JOIN activity AS a ON a.customer_id = f.customer_id
GROUP BY f.cohort_month
ORDER BY f.cohort_month;
 cohort_month | cohort_size | returned_later 
--------------+-------------+----------------
 2025-01-01   |           2 |              2
 2025-02-01   |           1 |              1
 2025-03-01   |           1 |              0
 2025-04-01   |           1 |              0
(4 rows)

Read the January cohort: 2 customers started then, and both ordered again in a later month. The full production version adds a "months since cohort" column and pivots it into the classic retention triangle — same CTEs, one more date_trunc subtraction; at shopdb's size the summary carries the idea without drowning it in machinery.

🧪 Quick quiz — answer from memory, then check.

  1. What defines a customer's cohort here?
  2. Why count(DISTINCT ...) for returned_later?
Show the answers
  1. The month of their first order — min(order_date) truncated to month.
  2. A customer active in three later months must count once, not three times.

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

Search the guide