Calculate retention rate per user from transactions
Quick Overview
Write SQL to compute retention rate grouped by user from transactions, handling nulls and duplicates.
Walmart
8
Write SQL to compute retention rate grouped by user from transactions, handling nulls and duplicates.
Walmart analysts track repeat purchasing to understand customer loyalty across stores and online. This SQL question checks whether you can define retention precisely, bucket transactions by period, and handle nulls and duplicate rows so the numbers can be trusted.
What the Interviewer Expects
- Clarify the retention definition and the time period (for example month over month)
- Filter out null user ids and dates and deduplicate transactions
- Bucket by month with DATE_TRUNC and compare consecutive periods per user
- Compute the retention rate with a safe division
- Sanity check results on a small sample of users
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you compute cohort retention by first purchase month instead?
- How would you treat a user who skips a month and then returns?
- How would you write this with window functions such as LAG?
- How would you make this efficient on billions of rows?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Problem Understanding
The goal is to calculate the retention rate per user based on transaction data from Walmart. The retention rate typically refers to the percentage of users who continue to make purchases over time. In...
Approach
- Identify Unique Users: Start by selecting distinct user IDs from the transactions table.
- Count Transactions: For each user, count the number of transactions they made within a specifie...