← All Exercises

Monthly Cohort Retention with Conditional Counts

advancedsql~20min

Background

Cohort retention separates growth from repeat behavior. Grouping customers by acquisition month shows whether newer cohorts stick around as well as older ones.

Problem

Given an orders table, assign each customer to the month of their first order, then report each cohort's size and how many customers ordered again in the following month.

Input

A PostgreSQL orders table with id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id integer NOT NULL, ordered_at date NOT NULL, and total numeric(10,2).

Output

One row per acquisition month with cohort_month, cohort_size, retained_month_1, and retention_pct rounded to one decimal, ordered by cohort_month.

Sample tests

Sample 1

Input: customer 1 orders 2026-01-05 and 2026-02-10; customer 2 orders 2026-01-20 and 2026-02-18; customer 3 orders 2026-02-02 and 2026-03-15; customer 4 orders 2026-02-20
Expected: 2026-01-01 | 2 | 2 | 100.0
2026-02-01 | 2 | 1 | 50.0

Sample 2

Input: a separate dataset with only customer 5, who places one order on 2026-03-01 and never orders again
Expected: 2026-03-01 | 1 | 0 | 0.0

Your solution

Learning objective

Combine cohort construction, date arithmetic, DISTINCT counting, and FILTER to produce retention metrics.