Interview Questions/SQL/Monthly Customer Retention Rate

Monthly Customer Retention Rate

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

Medium

Description

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

Database Schema (Inferred)

Purchases

Column NameExample Value
id1
customer_id1
purchase_date2023-01-05

Example

Purchases

idcustomer_idpurchase_date
112023-01-05
222023-01-10
332023-01-20
412023-02-08
522023-02-15
612023-03-01
742023-03-10
852023-04-01

Output

monthactive_customersretained_next_month
2023-0132
2023-0221
2023-0320
2023-0410

Explanation:

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.

SQL Editor
Loading...

Purchases

idcustomer_idpurchase_date
112023-01-05
222023-01-10
332023-01-20
412023-02-08
522023-02-15
612023-03-01
742023-03-10
852023-04-01

Output

monthactive_customersretained_next_month
2023-0132
2023-0221
2023-0320
2023-0410