Skip to main content

Cohort retention or consecutive active-day streak query

Compute Day-1 retention (fraction of users who signed up on day D and logged an event on day D + 1).

Official Reference

Model Answer & Explanation

WITH daily AS (
  SELECT DISTINCT user_id, created_at::date AS day FROM events
)
SELECT u.signup_date,
       COUNT(u.id) AS cohort_size,
       ROUND(COUNT(d.user_id)::numeric / COUNT(u.id), 3) AS d1_retention
FROM users u
LEFT JOIN daily d
  ON d.user_id = u.id AND d.day = u.signup_date + 1
GROUP BY u.signup_date
ORDER BY u.signup_date;

Deduplicate user activity per calendar day first so multiple events per day don’t double-count. Left-join signup_date to activity on activity_date = signup_date + INTERVAL '1 day' and compute COUNT(retained_user) * 1.0 / COUNT(signup_user). For consecutive streaks, use the islands-and-gaps trick: activity_date - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY activity_date))::int.

Follow-up Interview Question · Why do timezone conversions matter when truncating UTC timestamps into user calendar days?

Module Context & References

PostgreSQL & Redis · Practice SQL & schema drills The classic SQL queries, locking patterns and optimization problems tested repeatedly
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.