Interview Questions/SQL/Monthly Customer Retention Rate

Monthly Customer Retention Rate

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Monthly Customer Retention Rate

You are given a table of customer purchases. Write a SQL query to compute, for each month: the number of distinct active customers in that month (active_customers), and the number of those customers who also made a purchase in the immediately following month (retained_next_month). Return month, active_customers, and retained_next_month ordered by month. Table: Purchases

Column NameTypeDescription
idINTPrimary key
customer_idINTID of the customer
purchase_dateDATEDate of the purchase

Examples

Example 1

Build a distinct (customer_id, month) CTE. Then LEFT JOIN it to itself shifted by one month to count customers who appear in both the current and next month.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

query.sql