Seven-Day Return Rate from a Daily Posting Log
SQL & DataModel answerLast updated
From a per-day post count table, find each user's first active date, their first-week post total, and the share of users who were active on the seventh day of their life on the platform.
You are given a table post_activity that records how many posts each user made on each calendar day.
| Column | Meaning |
|---|---|
| user_id | identifier of the user |
| post_date | calendar date of the activity |
| posts | number of posts made by the user that day |
Sample data:
| user_id | post_date | posts |
|---|---|---|
| 1 | 2023-01-01 | 3 |
| 1 | 2023-01-02 | 2 |
| 2 | 2023-04-10 | 1 |
| 2 | 2023-04-11 | 4 |
| 3 | 2023-05-05 | 5 |
There is no separate signup table, so a user's join date has to be inferred from this log.
Tasks
- For each user, determine the join date, defined as the earliest
post_dateon which they posted. - For each user, compute the total number of posts made during their first 7 days on the platform (the join date and the following six days).
- Compute the Day-7 retention rate: the number of users who posted on their 7th day, divided by the number of users who posted on their 1st day.
Write the solution in SQL, and optionally show the equivalent in Python (pandas).
What to cover in your answer
- State your convention for numbering days (is the join date Day 1 or Day 0?) and show how the choice affects the query.
- Show the output for the sample data.
- Discuss edge cases: duplicate rows for one user-day, rows with zero posts, users too new to have reached Day 7, and users with gaps in activity.
Hints
Hint 1
Attach each user's join date to every one of their rows without collapsing the table. A window MIN over a partition by user does exactly that.
Hint 2
Subtract the join date from each post_date to get a day offset, then use CASE expressions on that offset: one to sum posts for offsets 0 to 6, and others to produce 0/1 flags for offset 0 and offset 6.
Hint 3
Take MAX of each flag per user to get a boolean, then divide the sum of the Day-7 flags by the sum of the Day-1 flags. Remember to avoid integer division and to think about users who joined too recently to have a Day 7.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Pin down the definitions first
The prompt is ambiguous, so state your conventions before writing code:
- Join date: the user's earliest
post_datewithposts > 0. - Day N: join date plus (N − 1) days. Day 1 is offset 0 and Day 7 is offset 6.
- First 7 days: offsets 0 through 6, inclusive.
- Day-7 retention: users active at offset 6 divided by users active at offset 0.
Some teams treat "Day 7" as seven days after joining (offset 7). Mention this and note it is a one-character change in the query. Also note that because the join date is derived from the first post, every user is active on Day 1 by construction, so the denominator equals the number of users. Keeping the explicit Day-1 flag is still wise in case a real signup table is introduced later.
Approach
- Clean to one row per user per day. Sum
postsby(user_id, post_date)and drop rows with zero posts, so duplicates and placeholder rows cannot distort the join date or the activity flags. - Window function.
MIN(post_date) OVER (PARTITION BY user_id)gives the join date on every row without collapsing the data. It must be computed over the full history, before any date filtering. - Date arithmetic.
offset = post_date - join_date. - Conditional aggregation per user.
- Sum of posts where offset is between 0 and 6.
MAXof a 0/1 flag for offset = 0.MAXof a 0/1 flag for offset = 6.
- Ratio. Sum the Day-7 flags over the sum of the Day-1 flags, cast to a decimal type.
SQL (PostgreSQL)
WITH daily AS (
SELECT user_id, post_date, SUM(posts) AS posts
FROM post_activity
WHERE posts > 0
GROUP BY user_id, post_date
),
with_join AS (
SELECT user_id, post_date, posts,
MIN(post_date) OVER (PARTITION BY user_id) AS join_date
FROM daily
),
per_user AS (
SELECT user_id,
join_date,
SUM(CASE WHEN post_date - join_date BETWEEN 0 AND 6
THEN posts ELSE 0 END) AS posts_first_7d,
MAX(CASE WHEN post_date - join_date = 0 THEN 1 ELSE 0 END) AS active_d1,
MAX(CASE WHEN post_date - join_date = 6 THEN 1 ELSE 0 END) AS active_d7
FROM with_join
GROUP BY user_id, join_date
)
-- Parts 1 and 2
SELECT user_id, join_date, posts_first_7d FROM per_user;
-- Part 3 (same CTEs)
-- SELECT SUM(active_d7)::numeric / NULLIF(SUM(active_d1), 0) AS day7_retention
-- FROM per_user;
Dialect notes: MySQL uses DATEDIFF(post_date, join_date); BigQuery uses DATE_DIFF(post_date, join_date, DAY). The ::numeric cast avoids integer division and NULLIF avoids division by zero on empty input.
Result on the sample
| user_id | join_date | active offsets | posts_first_7d | Day 1 | Day 7 |
|---|---|---|---|---|---|
| 1 | 2023-01-01 | 0, 1 | 5 | 1 | 0 |
| 2 | 2023-04-10 | 0, 1 | 5 | 1 | 0 |
| 3 | 2023-05-05 | 0 | 5 | 1 | 0 |
No one posted at offset 6, so retention is 0 / 3 = 0.0.
Python (pandas)
import pandas as pd
def day7_retention(df: pd.DataFrame):
d = df.loc[df["posts"] > 0].copy()
if d.empty:
return pd.DataFrame(), float("nan")
d["post_date"] = pd.to_datetime(d["post_date"])
d = d.groupby(["user_id", "post_date"], as_index=False)["posts"].sum()
d["join_date"] = d.groupby("user_id")["post_date"].transform("min")
d["offset"] = (d["post_date"] - d["join_date"]).dt.days
d["in_window"] = d["posts"].where(d["offset"].between(0, 6), 0)
d["is_d1"] = (d["offset"] == 0).astype(int)
d["is_d7"] = (d["offset"] == 6).astype(int)
per_user = d.groupby(["user_id", "join_date"], as_index=False).agg(
posts_first_7d=("in_window", "sum"),
active_d1=("is_d1", "max"),
active_d7=("is_d7", "max"),
)
n1 = per_user["active_d1"].sum()
rate = per_user["active_d7"].sum() / n1 if n1 else float("nan")
return per_user, rate
Why it is correct
- The window
MINruns over each user's whole history, so the join date is never distorted by a later filter. - Taking
MAXof 0/1 flags yields a per-user boolean, so nobody is counted twice even with several rows on one day. - Pre-aggregating by day merges duplicate rows (their posts add up) without inflating activity counts.
- Filtering
posts > 0stops a zero-post row from becoming a join date or counting as activity.
Complexity
With n input rows: time is O(n log n) with sort-based partitioning, effectively O(n) with hash aggregation; space is O(n) for intermediates and O(U) for the final per-user output.
Edge cases and common mistakes
- Immature cohorts. A user who joined fewer than 7 days before the end of the data cannot have a Day 7 yet, which deflates the rate. Restrict both numerator and denominator to users with
join_date <= max(post_date) - 6. This is the most valuable refinement to raise. - Gaps. A user active on Day 1 and Day 7 but not in between still counts. That is point-in-time ("classic") retention. "Rolling" retention instead counts anyone active on Day 7 or later; name the distinction.
- Off-by-one errors. Mixing Day 1 = offset 0 with
BETWEEN 0 AND 7yields eight days. Keep the convention consistent. - Integer division. Forgetting the numeric cast returns 0 or 1 instead of a fraction.
- Filtering before computing the join date. Restricting to a date range first can mislabel users whose true first post is outside it.
- Time zones. If
post_datecomes from timestamps, day boundaries depend on the zone; confirm it is the user's local date or a fixed standard. - Empty input.
NULLIFreturns NULL rather than a division error.
What a strong answer includes
Explicit day-numbering convention, the three-step structure (window, offset, conditional aggregation), a traced sample result, the immature-cohort adjustment, and a clear statement of which retention definition is being used.