User Retention & Engagement Questions
Measuring and improving how users stick with a product after they first convert: retention rate and cohort retention curves (day 1, day 7, day 30, and longer horizons), churn rate, reactivation and resurrection of lapsed users, and engagement-depth signals such as DAU, WAU, MAU, and the DAU/MAU stickiness ratio. Covers defining and computing these metrics, including basic SQL and event-log implementations, diagnosing where and why a retention curve breaks (onboarding gaps, feature-adoption gaps, seasonal or cohort-specific effects), designing experiments and product interventions that deepen habitual usage, cohort-based lifetime value (LTV), and communicating retention findings to stakeholders. This is the post-acquisition, repeat-usage side of the user lifecycle: getting a first-time visitor through signup or first purchase is covered by the companion topic Conversion Funnel Optimization, and pure-SQL implementation depth at large scale (approximate-distinct computation, survival-curve modeling, multi-state subscription churn state machines, and standalone timezone-aware day bucketing) is covered by the companion topic Advanced SQL: Metric Monitoring, Anomaly Detection, and Data Correctness at Scale.
Explain how to compute minimum sample size for an A/B test where the primary metric is 14-day retention rate. Assume baseline 14-day retention is 20%, desired uplift detection is 2 percentage points absolute, alpha=0.05, power=0.8. Describe the formula and any assumptions, including treatment effect stability across time.
Sample Answer
Direct answer
Use the standard two-proportion sample-size formula for detecting an absolute difference between a baseline retention rate and a target retention rate: n=(p2−p1)2(zα/2+zβ)2[p1(1−p1)+p2(1−p2)] per arm, where p1 is baseline 14-day retention, p2=p1+MDE is the target rate, and zα/2, zβ are the standard-normal critical values for your significance level and power. Plugging in the given numbers requires roughly 6,507 users per arm, about 13,014 total.
Structured elaboration
Where the formula comes from. Under the normal approximation to the binomial, the variance of a single proportion p^ estimated from n users is p(1−p)/n. The variance of the DIFFERENCE between two independent proportions is the sum of their variances, p1(1−p1)/n+p2(1−p2)/n. Solving for the n that makes the test have significance level α (two-sided) and power 1−β against a true difference of p2−p1 gives the formula above; it is exact in the large-sample normal approximation, which is comfortable here since p1≈0.20 and n in the thousands keeps np(1−p) well above the usual rule-of-thumb minimum of 5-10.
Plugging in the given numbers. p1=0.20, p2=0.22 (a 2 percentage-point absolute uplift), α=0.05 two-sided so zα/2=z0.025≈1.96, power =0.80 so zβ=z0.20≈0.8416.
n=(0.02)2(1.96+0.8416)2[0.20(0.80)+0.22(0.78)] n=0.0004(2.8016)2×(0.16+0.1716)=0.00047.849×0.3316≈6,507 per armAssumption 1: treatment-effect stability across time. The formula assumes the true 2pp uplift is constant for the whole 14-day measurement window and does not itself validate that assumption; if the treatment's effect on retention is actually front-loaded (a big day-1 to day-3 bump that fades by day 14) or back-loaded (no visible effect until day 10+), the POWER calculation above is still arithmetically correct for detecting a 2pp difference AT day 14 specifically, but the experiment's DURATION and interim-monitoring plan need to account for that shape separately; a novelty-driven early spike that decays can produce a false sense of a working experiment if you peek at day 3 instead of waiting for the pre-registered day-14 read.
Assumption 2: independence between users. The formula assumes each user's retention outcome is an independent Bernoulli draw. Network effects (one user's retention behavior influencing another's, common in social or collaborative products) violate this and effectively reduce the true sample size below the nominal n, which is a real risk for any product where users interact with each other.
Assumption 3: one measurement per user, no repeated exposure ambiguity. The formula assumes a clean per-user binary outcome (retained at day 14, yes or no); if users can be re-randomized or re-enter the experiment, the unit of analysis needs to be fixed before this formula applies.
Worked example
The full derivation above IS the worked example (values in the direct answer section were computed with a pinned, stdlib-only inverse-normal solver rather than asserted from memory, described below). To sanity-check the arithmetic direction: doubling the MDE from 2pp to 4pp should cut the required sample size by roughly 4x, since n scales with 1/(p2−p1)2. At MDE=4pp, p2=0.24: n=(2.8016)2×(0.16+0.24×0.76)/(0.04)2=7.849×0.3424/0.0016≈1,680 per arm, about a 3.9x reduction from 6,507, consistent with the inverse-square relationship (not exactly 4x because p2(1−p2) also changes slightly as p2 moves).
Trade-offs and pitfalls
- Using relative uplift language when the formula wants absolute. "2 percentage points" (0.20 to 0.22) is very different from "2% relative uplift" (0.20 to 0.204); confusing the two changes p2−p1 by an order of magnitude and inflates or deflates n correspondingly. Always confirm which one a stakeholder means before computing.
- Ignoring practical significance vs. statistical significance. A well-powered test for a 2pp absolute lift is a real commitment: at n≈6,500/arm this experiment can run for weeks depending on traffic, and a smaller MDE (say 0.5pp) would multiply the required sample size roughly 16x, which may simply not be feasible in the available traffic and timeline; the sample-size calculation should inform what MDE is realistic to chase, not just be solved mechanically for whatever MDE a stakeholder first proposes.
- Skipping a sequential or group-sequential design when the team is going to look at the data before the target n is reached anyway. If interim peeking is inevitable in practice, the fixed-horizon formula above needs to be paired with an alpha-spending correction (e.g., O'Brien-Fleming bounds) or the true false-positive rate will exceed the nominal 5%.
You inspect a retention curve that drops steeply in the first week, then hips slightly after week 8. List three plausible product or data causes for (a) the steep early drop and (b) the late bump around week 8. For each cause describe an experiment or analysis you would run to validate it.
Sample Answer
Direct answer
A steep early drop almost always points at onboarding friction, a mismatch between what acquisition promised and what the product delivers, or an instrumentation problem; a later small bump around week 8 almost always points at a delayed value-realization moment, a recurring external trigger (a billing or seasonal cycle), or a segment-mix effect from a specific acquisition cohort entering the data. For each, the right validating check is one that can isolate the specific mechanism, not just confirm that the pattern is real.
Structured elaboration
(a) Three plausible causes for the steep early drop, each with its validation:
- Onboarding friction. Users hit a confusing or broken step early in the flow (a required setup step, a slow first-load, an unclear next action) and abandon before reaching real value. Validate by building a step-level funnel THROUGH onboarding specifically (not just the retention curve) and checking whether the drop-off concentrates at one identifiable step; a session-replay or drop-off-point analysis on a sample of abandoning users confirms whether it's a UX problem versus a broader disengagement.
- Acquisition-value mismatch. A marketing campaign or channel promised something the product does not actually deliver (wrong expectations set pre-signup), so users who arrive expecting X and find Y leave immediately. Validate by segmenting the early drop by acquisition channel/campaign; if the drop is concentrated in one specific channel rather than spread evenly, that channel's messaging (not the product) is the likely cause.
- Instrumentation or data-quality issue. A tracking bug undercounts early activity (a client-side event failing to fire on first launch, a bot-traffic spike inflating the cohort denominator without corresponding real activity). Validate by cross-checking the retention-curve activity count against an independent signal (server-side login logs, or billing/account-status records) for the same cohort; a genuine product/UX cause should agree across independent measurement systems, while an instrumentation bug typically will not.
(b) Three plausible causes for the late bump around week 8, each with its validation:
- Delayed value realization. Some users take longer to reach the product's core value (a B2B tool where a user needs a full billing or reporting cycle before the product proves itself, for example) and their engagement genuinely increases once that occasion arrives. Validate by checking whether the bump timing lines up with a known recurring product or business cycle (monthly billing, a report deadline) and whether it correlates with a specific in-product milestone rather than pure calendar time.
- A recurring external trigger. A weekly or monthly external event (payday, a subscription renewal reminder email, a seasonal occasion) pulls dormant users back on a predictable schedule. Validate by checking whether the bump timing correlates with any scheduled outbound communication (an automated re-engagement email that fires at a fixed day-count) or an external calendar event, which would explain a bump at a fairly consistent offset across cohorts.
- Cohort-composition effect, not a true behavioral bump. If the "cohort" in this curve mixes several acquisition sub-groups with different natural cadences, a slower-cadence sub-group's FIRST activity could land disproportionately around week 8, creating an apparent uptick in the aggregate curve that is really a composition artifact rather than any single user's retention improving. Validate by re-running the curve segmented by acquisition source or user type; if the bump disappears once segmented, it was a mixing artifact, not a real behavioral phenomenon.
Worked example
A retention curve for a 10,000-user cohort: week 1 retention is 22% (a steep drop from day 0's 100%), and the curve, which had been gently declining, ticks up from 9.5% at week 7 to 10.8% at week 8 before resuming its decline. Applying the diagnostic above: segmenting week-1 retention by acquisition channel shows paid social at 14% versus organic search at 31%, more than double, immediately narrowing cause (a) toward an acquisition-message mismatch concentrated in paid social rather than a universal onboarding bug (which would show up evenly across channels). Segmenting the week-8 bump by acquisition month shows it is driven almost entirely by users acquired in the cohort's SECOND acquisition wave, who make up a larger share of week-8's active base than of the overall cohort, supporting cause (b)(3), a composition effect, over a genuine week-8 value-realization moment.
Trade-offs and pitfalls
- Treating "the curve looks like this" as self-explanatory is the most common mistake. A shape (steep drop, small bump) is a symptom with multiple plausible mechanisms behind it; presenting only the shape without a segmented breakdown that actually distinguishes between the candidate causes is descriptive, not diagnostic.
- A single validating check rarely rules out more than one hypothesis at once. Channel segmentation addresses acquisition mismatch specifically; it says nothing about onboarding friction WITHIN a channel, so a thorough diagnosis typically needs to run 2-3 of the checks above in combination before recommending a fix.
- Chasing the week-8 bump as if it were the headline finding, when the steep early drop dwarfs it in absolute impact, is a common prioritization error: a bump from 9.5% to 10.8% recovers a small fraction of the ~78 percentage points already lost by week 1, so the early-drop investigation should almost always get first priority in a resource-constrained team.
You receive an events table with duplicate rows, partial user IDs, and multiple device IDs per user. Provide a step-by-step SQL or Python approach to deduplicate events, map multiple devices to canonical users, and build a canonical users table suitable for retention analysis. Explain assumptions and pitfalls (e.g., identity resolution, cross-device linking).
Sample Answer
Direct answer
Handle this in three explicit passes, each solving a distinct problem: first collapse exact duplicate rows, then resolve partial/short user IDs to their real full ID via an explicit identity mapping, then merge multiple device IDs belonging to the same real person under one canonical user ID, so the final table has exactly one row per genuinely distinct event, attributed to exactly one canonical identity per real user, regardless of how many raw IDs or devices that person appears under.
Structured elaboration
Pass 1: deduplicate exact repeats. A SELECT DISTINCT (or, in a Python approach, inserting rows into a set keyed on (user_id, device_id, event_name, occurred_at)) collapses identical rows, which commonly arise from client-side retry logic or double-fired SDK calls. This has to happen BEFORE any identity resolution, since resolving IDs first and then deduplicating risks accidentally treating two genuinely distinct events (that happen to look similar after ID normalization) as duplicates.
Pass 2: resolve partial/truncated user IDs. A short or partial user_id (a truncated string, a legacy ID format from before a migration) needs to be mapped to its correct full/canonical form via an explicit ID-MAPPING TABLE, not inferred by string-matching heuristics alone (a heuristic like "IDs that are prefixes of each other are probably the same user" is dangerous, since it can produce false merges between two genuinely different users whose IDs happen to share a prefix by coincidence). In a real pipeline, this mapping table is typically populated from an authoritative source (a login/merge event, an account-linking flow, or a backend user-identity service), not derived from the events table itself.
Pass 3: cross-device linking. Multiple device IDs belonging to the same real person (a user on their phone and their laptop) need to roll up to one canonical user, typically resolved via a stable identifier that persists across devices (an authenticated login, an email hash) rather than a device-local identifier, which by definition cannot see across devices at all. Where a persistent authenticated ID exists, this is the primary key to canonicalize on; device ID alone should never be treated as a stand-in for user identity in a retention or engagement calculation, since it would double-count a single habitual user who happens to use two devices as if they were two separate users.
Assumptions and pitfalls, named explicitly. The mapping used for identity resolution is only as trustworthy as its SOURCE: if it comes from a login/merge event stream, its own completeness and correctness need to be validated (are there users who never went through the merge flow and remain incorrectly split across two IDs); a canonical-user rollup that MERGES two genuinely different real people (a false positive, e.g. a shared family device wrongly resolved to one identity) silently overstates that "person's" retention, while a rollup that FAILS to merge a real person's two devices (a false negative) silently understates it by treating them as two separate lower-activity users; both failure directions are real and, unlike a query error, produce a plausible-looking wrong number rather than an obvious failure.
Worked example
Six raw rows: an exact duplicate, a truncated user_id belonging to a known user, a second device for that same user, and a genuinely separate second user:
import sqlite3
conn = sqlite3.connect(':memory:')
conn.executescript("""
CREATE TABLE raw_events (row_id INTEGER, user_id TEXT, device_id TEXT, event_name TEXT, occurred_at TEXT);
INSERT INTO raw_events VALUES
(1,'u100','dA','open','2026-01-01 09:00:00'),
(2,'u100','dA','open','2026-01-01 09:00:00'),
(3,'u100','dB','open','2026-01-02 10:00:00'),
(4,'u1', 'dC','open','2026-01-03 11:00:00'),
(5,'u200','dD','open','2026-01-01 12:00:00'),
(6,'u200','dD','open','2026-01-04 09:00:00');
""")
# Row 2 is an exact duplicate of row 1; row 3 is the same user on a second device;
# row 4 is a truncated ID belonging to the same person as u100; rows 5-6 are a
# genuinely different, separate user.
# Pass 1: exact-duplicate removal
conn.execute("CREATE TABLE deduped AS SELECT DISTINCT user_id, device_id, event_name, occurred_at FROM raw_events;")
# Pass 2/3: identity resolution via an explicit mapping (in production, sourced
# from an authoritative login/merge event stream, not inferred by string heuristics)
id_map = {'u100': 'canon_1', 'u1': 'canon_1', 'u200': 'canon_2'}
conn.execute("CREATE TABLE canonical_events AS SELECT user_id AS raw_user_id, device_id, event_name, occurred_at FROM deduped;")
conn.execute("ALTER TABLE canonical_events ADD COLUMN canonical_user_id TEXT")
for raw_id, canon_id in id_map.items():
conn.execute("UPDATE canonical_events SET canonical_user_id = ? WHERE raw_user_id = ?", (canon_id, raw_id))
cur = conn.execute(
"SELECT canonical_user_id, COUNT(DISTINCT device_id) AS distinct_devices, COUNT(*) AS event_count "
"FROM canonical_events GROUP BY canonical_user_id ORDER BY canonical_user_id"
)
for row in cur.fetchall(): print(row)
Output (actually executed): raw_events had 6 rows, deduped had 5 (row 2's exact duplicate removed). Final result:
canonical_user_id | distinct_devices | event_count
canon_1 | 3 | 3
canon_2 | 1 | 2
canon_1 correctly merges u100 and u1 into one identity spanning 3 distinct devices (dA, dB, dC) and 3 events; canon_2 (u200) remains its own separate identity with 1 device and 2 events, correctly NOT merged with canon_1 despite superficially being a different-length string from u1, since the mapping is explicit rather than heuristic.
Trade-offs and pitfalls
- String-prefix or edit-distance heuristics for identity resolution ("u1" looks like a prefix of "u100," so maybe they're related) are exactly the kind of shortcut that produces confident, silent false merges; the worked example's explicit
id_mapstands in for what should be a validated, authoritative mapping source in a real pipeline, not a heuristic guess. - Running deduplication AFTER identity resolution instead of before risks conflating "these are the same event, seen twice" with "these are two different events from the same real person," collapsing legitimate repeat activity into a single row; the pass ORDER in this answer (dedup first, then resolve identity) is a deliberate choice, not an arbitrary one.
- A canonicalization pipeline built once and never re-validated will silently drift as new merge events, new devices, and new edge cases (shared devices, ID reuse after account deletion) accumulate over time; treating identity resolution as a one-time cleanup rather than an ongoing, periodically-audited process is a common way a "clean" canonical table degrades in accuracy months after it was built.
You're asked to present retention insights to executives in a 10-minute slot. Describe the structure of a one-page slide that communicates the issue, impact, and recommended actions. Which visual(s) would you include and what numbers should be highlighted to drive decisions?
Sample Answer
Direct answer
Structure the ten minutes as issue, impact, recommendation, in that order, on a single slide with one dominant visual (a retention curve or cohort comparison, whichever shows the finding most directly) and no more than 2-3 highlighted numbers, since an executive audience needs the takeaway and the ask, not the full analytical path that produced them.
Structured elaboration
The slide's narrative structure. Lead with the ISSUE in one sentence a non-analyst can immediately parse ("week-2 retention for new signups has dropped 8 points over the last month"), state the IMPACT in business terms the audience already cares about (revenue at risk, users lost, or a comparison to a target the team is accountable to), then close with the RECOMMENDED ACTION and what you need from the room (a decision, a resource, an approval). This ordering matters: leading with methodology or with a wall of secondary metrics buries the ask the meeting actually exists to resolve.
Which visual(s) to include. One primary visual, chosen to show the finding as directly as possible rather than to demonstrate analytical thoroughness: a retention curve with the affected cohort highlighted against a baseline band (for a curve-shaped finding), or a simple before/after comparison bar for a single point-in-time metric. Avoid a cohort heatmap or a dense multi-line chart with many cohorts on an executive slide, both of which are more useful for the PM's working layer than for a ten-minute headline read; if the underlying analysis used a heatmap to FIND the issue, the executive slide should show a simplified, single-highlighted-line derivative of it, not the raw heatmap itself.
Which numbers to highlight. Two or three numbers maximum, each doing distinct work: the SIZE of the problem (how far off the metric is from where it should be), the SCOPE (how many users or how much revenue this affects, translating an abstract percentage into something the audience already has intuition for), and the ASK (what specifically you want approved or decided). Every additional number beyond these dilutes attention from the ones that actually drive the decision.
Anticipating the first follow-up question. An executive's most likely immediate question is "are you sure this isn't just noise/seasonality/something we already knew about," so having ONE line of confidence-building context ready (even if not on the main slide) - such as "this is a step-change, not normal week-to-week variation" - closes the most predictable objection before it derails the ten minutes into a methodology debate.
Worked example
A concrete slide for a genuine 8-point week-2 retention drop: headline text "Week-2 retention for new signups down 8 points (34% to 26%) over the past 4 weeks, a step-change not explained by normal variation." Visual: a single retention-curve chart with the current cohort's line in a highlighted color against a shaded band representing the range of the prior 6 cohorts, making the current cohort's departure from normal visually obvious without requiring the audience to read individual data points. Highlighted numbers: "8-point drop" (size), "roughly 1,200 fewer retained users per week at current signup volume" (scope, translating the percentage into a concrete headcount), and "requesting approval to pause the underperforming acquisition channel identified as the likely cause" (the ask). This structure lets someone walk in cold, read the slide in 15 seconds, and understand exactly what happened, how much it matters, and what decision is being requested, before the presenter says a word.
Trade-offs and pitfalls
- Including the full analytical journey (every hypothesis tested, every dead end) on the executive slide, rather than just the conclusion and one line of supporting confidence, is the most common way a ten-minute slot turns into a much longer, less effective conversation than intended; that detail belongs in an appendix slide or a follow-up document, available if asked for, not on the primary slide.
- Translating a percentage into an absolute headcount or revenue figure (as in "1,200 fewer retained users per week") is what makes the scope number land for a non-technical audience; a bare percentage, however accurate, often fails to convey magnitude the way a concrete count of real users does.
- A slide with no clear ask forces the room to improvise a next step in real time, which is both less efficient and more likely to produce a vague, non-committal outcome than a slide that arrives with a specific, pre-formed recommendation the room can approve, modify, or reject.
Delivery pacing within the ten minutes
A rough time budget helps keep the slot from drifting into an open-ended discussion before the ask has landed: roughly 90 seconds stating the issue and impact off the slide itself, 2-3 minutes walking the visual (pointing at exactly where the highlighted cohort departs from the baseline band, not re-reading every axis label), 2-3 minutes on the recommendation and what's being requested, and the remaining time held open for questions, with the pre-prepared confidence-building line ready as the first response if the expected 'is this just noise' question comes up. Presenters who spend the first several minutes on background and methodology often find the room's attention has already drifted by the time the actual ask arrives, which is the practical cost of the structural mistake described above, not just a theoretical one.
Given a PostgreSQL events table with schema events(user_id bigint, event_name text, occurred_at timestamp), write a SQL query that builds a daily cohort retention table showing Day 0, Day 1, Day 7, and Day 30 retention rates for cohorts defined by users' first event date. Output should include cohort_date and retention columns for each day. Explain assumptions about timezones and users with multiple events.
Sample Answer
Direct answer
Anchor every user to a single cohort date (the calendar date of their first-ever event), then for each cohort date compute the fraction of that cohort's users who show ANY activity on cohort_date+0, +1, +7, and +30. A user with several events on the same day counts once (deduplicate with COUNT(DISTINCT user_id)), and "activity" should mean any event in the table, not a specific event_name, unless the interview scenario says otherwise.
Structured elaboration
Step 1: derive the cohort anchor. first_event AS (SELECT user_id, MIN(date(occurred_at)) AS cohort_date FROM events GROUP BY user_id). This is the single most consequential design decision in the query: every retention day is measured relative to this date, so if a user's true "first touch" happened outside this table (a different upstream event stream), the cohort_date here is wrong and everything downstream inherits the error.
Step 2: build a per-user set of distinct activity dates. SELECT DISTINCT user_id, date(occurred_at) AS activity_date FROM events. The DISTINCT here is what makes multiple same-day events collapse to one row, so a power user who fires 50 events on day 7 contributes exactly the same weight to day7_retention as a user who fires 1.
Step 3: express each activity date as an offset from the user's own cohort_date, day_offset = activity_date - cohort_date (in Postgres, activity_date - cohort_date on two date columns returns an integer directly; the worked example below uses SQLite's julianday() difference, which is the equivalent idiom for that engine). This turns "was the user active on 2026-01-08" into "was the user active at offset 7", which is what lets every cohort share the same day0/day1/day7/day30 columns regardless of when the cohort actually started.
Step 4: aggregate per cohort_date. For each of the four offsets, count distinct users at that offset and divide by the cohort's total size: COUNT(DISTINCT CASE WHEN day_offset = 7 THEN user_id END) / cohort_users. Using CASE WHEN ... THEN user_id END inside COUNT(DISTINCT ...) (rather than four separate subqueries) keeps the whole computation as one pass over cohort_activity.
Timezone assumption. occurred_at is a naive timestamp, not timestamptz, so the query above implicitly assumes it is already stored in one canonical timezone (commonly UTC, or the product's single reporting timezone). If events actually arrive with client-local timestamps across timezones, date(occurred_at) will misclassify events near midnight into the wrong calendar day for some users and not others, which quietly shifts users between cohorts and between day-offset buckets. The fix is to normalize at ingestion (store timestamptz and convert to one reporting timezone, e.g. date(occurred_at AT TIME ZONE 'UTC')), not inside this query.
Multiple-events assumption. A user who logs in at 00:05 and 23:55 on the same calendar day only ever contributes one row to activity, by design (step 2's DISTINCT). A user who is active on cohort_date itself only via a non-meaningful event (e.g., a push-notification-received event with no real engagement) will still count as day0-retained unless event_name is filtered to an "engagement" allowlist; whether to restrict to specific event types is a product decision that belongs in the WHERE clause of the activity CTE, not something the retention math itself resolves.
Worked example
Schema: events(user_id, event_name, occurred_at). Six users across two cohort days, with one user firing duplicate same-day events to test the dedup behavior directly:
CREATE TABLE events (user_id INTEGER, event_name TEXT, occurred_at TEXT);
INSERT INTO events VALUES
(1,'signup','2026-01-01 09:00:00'), (1,'open','2026-01-01 10:00:00'),
(1,'open','2026-01-01 11:00:00'), (1,'open','2026-01-01 12:00:00'), -- duplicate same-day events for u1
(1,'open','2026-01-02 09:00:00'), (1,'open','2026-01-08 09:00:00'), (1,'open','2026-01-31 09:00:00'),
(2,'signup','2026-01-01 09:00:00'), (2,'open','2026-01-02 09:00:00'),
(3,'signup','2026-01-01 09:00:00'), (3,'open','2026-01-02 09:00:00'), (3,'open','2026-01-08 09:00:00'),
(4,'signup','2026-01-01 09:00:00'),
(5,'signup','2026-01-02 09:00:00'), (5,'open','2026-01-03 09:00:00'), (5,'open','2026-01-09 09:00:00'),
(6,'signup','2026-01-02 09:00:00'), (6,'open','2026-01-03 09:00:00');
WITH first_event AS (
SELECT user_id, MIN(date(occurred_at)) AS cohort_date FROM events GROUP BY user_id
),
activity AS (
SELECT DISTINCT user_id, date(occurred_at) AS activity_date FROM events
),
cohort_activity AS (
SELECT f.user_id, f.cohort_date,
CAST(julianday(a.activity_date) - julianday(f.cohort_date) AS INTEGER) AS day_offset
FROM first_event f JOIN activity a ON a.user_id = f.user_id
),
cohort_size AS (
SELECT cohort_date, COUNT(*) AS cohort_users FROM first_event GROUP BY cohort_date
)
SELECT cs.cohort_date, cs.cohort_users,
ROUND(1.0*COUNT(DISTINCT CASE WHEN ca.day_offset=0 THEN ca.user_id END)/cs.cohort_users,4) AS day0,
ROUND(1.0*COUNT(DISTINCT CASE WHEN ca.day_offset=1 THEN ca.user_id END)/cs.cohort_users,4) AS day1,
ROUND(1.0*COUNT(DISTINCT CASE WHEN ca.day_offset=7 THEN ca.user_id END)/cs.cohort_users,4) AS day7,
ROUND(1.0*COUNT(DISTINCT CASE WHEN ca.day_offset=30 THEN ca.user_id END)/cs.cohort_users,4) AS day30
FROM cohort_size cs JOIN cohort_activity ca ON ca.cohort_date = cs.cohort_date
GROUP BY cs.cohort_date, cs.cohort_users ORDER BY cs.cohort_date;
Executed against SQLite (date()/julianday() are SQLite's date functions; Postgres would use plain date subtraction). Output:
cohort_date | cohort_users | day0 | day1 | day7 | day30
2026-01-01 | 4 | 1.0 | 0.75 | 0.5 | 0.25
2026-01-02 | 2 | 1.0 | 1.0 | 0.5 | 0.0
For the 2026-01-01 cohort (users 1,2,3,4): all 4 are active on day0 (1.0); user 4 never returns, so day1 drops to 3/4=0.75; only users 1 and 3 are back at day7 (2/4=0.5); only user 1 survives to day30 (1/4=0.25). User 1's three duplicate same-day rows on 2026-01-01 did not inflate day0 beyond 1/4, confirming the dedup logic works as designed.
Trade-offs and pitfalls
- "Any event" vs. a specific engagement event for the
activityCTE is a real modeling choice, not a detail: including low-signal events (app-opened due to a push notification, a background sync) as retention-qualifying activity inflates every day-offset number and can mask a genuine engagement problem. - Day30 near the end of the data window is left-censored, not zero by definition: a cohort acquired 5 days ago cannot have a valid day30 measurement yet, and reporting it as
NULL(whichCOUNT(DISTINCT CASE WHEN ...)naturally does when there is no matching offset) rather than0avoids silently reporting a false 0% retention for cohorts too young to have reached that offset. - The single-query,
CASE WHENpivot approach shown here scales to a handful of fixed day-offsets; for a full week_offset=0..N retention matrix (every day, or a much longer horizon), aCROSS JOINagainst a generated series of offsets plus aLEFT JOINback to activity is the more maintainable shape, since it does not require one hardcodedCASE WHENcolumn per offset.
Unlock Full Question Bank
Get access to all 43 User Retention & Engagement interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.