Daily Funnel Metrics and 1-Day Retention in SQL and pandas
SQL & DataModel answerLast updated
Build a validated event layer, then compute daily funnel counts, per-user first-event dates, and a one-day retention rate using SQL and pandas.
Setup
You are working with a product analytics database. Assume all timestamps are UTC and that "today" is 2025-09-01.
Schema
users (id INT, country STRING, hire_date DATE, visa_status STRING, is_remote BOOLEAN)
sessions (session_id INT, user_id INT, session_start TIMESTAMP, session_end TIMESTAMP, device STRING)
events (event_id INT, session_id INT, user_id INT, event_time TIMESTAMP, event_type STRING, metadata JSON)
Sample data
users
+----+---------+------------+-------------+-----------+
| id | country | hire_date | visa_status | is_remote |
+----+---------+------------+-------------+-----------+
| 1 | US | 2025-08-15 | H1B | 1 |
| 2 | CN | 2024-12-01 | GC | 0 |
| 3 | IN | 2025-06-01 | H1B | 1 |
+----+---------+------------+-------------+-----------+
sessions
+------------+---------+---------------------+---------------------+--------+
| session_id | user_id | session_start | session_end | device |
+------------+---------+---------------------+---------------------+--------+
| 10 | 1 | 2025-08-31 09:00:00 | 2025-08-31 09:30:00 | web |
| 11 | 1 | 2025-09-01 10:00:00 | 2025-09-01 10:07:00 | mobile |
| 12 | 2 | 2025-09-01 11:00:00 | 2025-09-01 11:20:00 | web |
| 13 | 3 | 2025-08-25 12:00:00 | 2025-08-25 12:10:00 | web |
+------------+---------+---------------------+---------------------+--------+
events
+----------+------------+---------+---------------------+------------+--------------------+
| event_id | session_id | user_id | event_time | event_type | metadata |
+----------+------------+---------+---------------------+------------+--------------------+
| 100 | 10 | 1 | 2025-08-31 09:01:00 | login | {} |
| 101 | 10 | 1 | 2025-08-31 09:05:00 | view | {"page":"pricing"} |
| 102 | 10 | 1 | 2025-08-31 09:10:00 | purchase | {"amount":100} |
| 103 | 11 | 1 | 2025-09-01 10:01:00 | login | {} |
| 104 | 11 | 1 | 2025-09-01 10:02:00 | view | {"page":"home"} |
| 105 | 12 | 2 | 2025-09-01 11:05:00 | login | {} |
| 106 | 12 | 2 | 2025-09-01 11:10:00 | purchase | {"amount":50} |
| 107 | 13 | 3 | 2025-08-25 12:05:00 | login | {} |
+----------+------------+---------+---------------------+------------+--------------------+
Part A — Daily funnel (SQL)
For every calendar date d in the closed range [2025-08-26, 2025-09-01], return one row with:
| column | definition |
|---|---|
date | the calendar date |
session_users | distinct users who had a session start on day d |
login_users | distinct users with a valid login event on day d |
purchase_users | distinct users with a valid purchase event on day d |
login_to_purchase | purchase_users / login_users as a decimal |
session_to_purchase | purchase_users / session_users as a decimal |
An event is valid only when it matches its session on both session_id and user_id, and event_time falls within [session_start, session_end] (inclusive). Any event that fails either check must be excluded. A user who triggers multiple events of the same type on the same day counts only once. Days with no activity must still appear in the output (with zeros or NULL for rates).
Part B — First-event dates and early-purchase flag (SQL)
For every user in the users table, compute:
first_login_date— earliest calendar date of a valid login eventfirst_purchase_date— earliest calendar date of a valid purchase eventwithin_7_days— TRUE iffirst_purchase_dateis betweenfirst_login_dateandfirst_login_date + 7 daysinclusive; FALSE otherwise (including when either date is missing)
Use the same valid-event definition as Part A.
Part C — One-day retention (Python / pandas)
Implement the function below using pandas DataFrames that follow the same schema as the tables above.
def retention_1d(as_of: str = "2025-09-01",
events_df: pd.DataFrame = None,
sessions_df: pd.DataFrame = None) -> float:
...
The function should:
- Build the same valid-event set (matching session window, both join keys) from the DataFrames.
- Identify every user whose first valid login date falls in the 7-day window
[as_of − 6 days, as_of](i.e., users who logged in for the first time recently). - Return the percentage (0–100) of those users who also have any valid event on the single day that is exactly one calendar day after their first login date.
In your solution, explicitly document how you handle:
- duplicate
event_idrows - events that have no matching session (orphaned events)
- events that fall outside the session time boundaries
- the treatment of UTC calendar days and the
as_ofboundary
Hints
Hint 1
Start by writing one 'valid events' CTE that enforces the three-way join condition (session_id, user_id, and the time window). Every subsequent query in Parts A and B reads from that CTE rather than from events directly — this keeps deduplication logic in one place and avoids repeating it.
Hint 2
For the date spine in Part A, generate all seven dates with a recursive CTE (or a VALUES list), then LEFT JOIN your aggregates onto it. This guarantees a row for every date even when no sessions or events exist that day. Use NULLIF on the denominator to avoid division-by-zero on empty days.
Hint 3
In Part C, think in terms of two sets: the cohort set — one row per user with their first_login_date — and the activity set — distinct (user_id, event_date) pairs from valid events. The retention check is just a left join between those two sets on user_id where the activity date equals first_login_date + one day, then a count of matches over cohort size.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
All three parts share a single foundational idea: define a valid event once, then build every metric on top of it. An event is valid when it joins to sessions on both session_id and user_id, and its event_time sits within [session_start, session_end] inclusive. Orphaned events (mismatched user or unknown session) and out-of-window timestamps are dropped at this step, not scattered across individual queries.
After that, each part reduces to deduplication and aggregation:
- Part A: count distinct
(user_id, date)per metric; left-join to a date spine for zero-fill. - Part B: take conditional
MINper user; compare the two dates. - Part C: join a cohort table to an activity table on
user_idand the target date.
Assumptions to state clearly:
- "Day d" for an event is
DATE(event_time); for a session it isDATE(session_start). - All timestamps are UTC; no timezone conversion is needed.
- Duplicate
event_idvalues are collapsed before any counting. - A user who purchases without a same-day login can push a conversion rate above 1.0. If the business wants a strict sequential funnel, purchasers should be intersected with that day's login set — worth flagging to the interviewer.
Part A (PostgreSQL)
WITH RECURSIVE
-- 1. Seven-day spine so empty days still appear
date_spine AS (
SELECT DATE '2025-08-26' AS d
UNION ALL
SELECT d + 1 FROM date_spine WHERE d < DATE '2025-09-01'
),
-- 2. Single source of truth: events that match their session
valid_events AS (
SELECT DISTINCT
e.user_id,
e.event_type,
CAST(e.event_time AS DATE) AS event_date
FROM events e
JOIN sessions s
ON s.session_id = e.session_id
AND s.user_id = e.user_id
AND e.event_time BETWEEN s.session_start AND s.session_end
),
-- 3. Per-day counts (one user per day, regardless of event count)
session_agg AS (
SELECT CAST(session_start AS DATE) AS d,
COUNT(DISTINCT user_id) AS n
FROM sessions
GROUP BY 1
),
login_agg AS (
SELECT event_date AS d, COUNT(DISTINCT user_id) AS n
FROM valid_events WHERE event_type = 'login'
GROUP BY 1
),
purchase_agg AS (
SELECT event_date AS d, COUNT(DISTINCT user_id) AS n
FROM valid_events WHERE event_type = 'purchase'
GROUP BY 1
)
SELECT
ds.d AS date,
COALESCE(sa.n, 0) AS session_users,
COALESCE(la.n, 0) AS login_users,
COALESCE(pa.n, 0) AS purchase_users,
ROUND(1.0 * COALESCE(pa.n, 0) / NULLIF(COALESCE(la.n, 0), 0), 4) AS login_to_purchase,
ROUND(1.0 * COALESCE(pa.n, 0) / NULLIF(COALESCE(sa.n, 0), 0), 4) AS session_to_purchase
FROM date_spine ds
LEFT JOIN session_agg sa ON sa.d = ds.d
LEFT JOIN login_agg la ON la.d = ds.d
LEFT JOIN purchase_agg pa ON pa.d = ds.d
ORDER BY ds.d;
Expected output:
| date | session_users | login_users | purchase_users | login→purchase | session→purchase |
|---|---|---|---|---|---|
| 2025-08-26 … 08-30 | 0 | 0 | 0 | NULL | NULL |
| 2025-08-31 | 1 | 1 | 1 | 1.0000 | 1.0000 |
| 2025-09-01 | 2 | 2 | 1 | 0.5000 | 0.5000 |
User 3's session and login are on 2025-08-25, outside the requested range, so they do not appear. The 1.0 * factor prevents integer division; NULLIF avoids division-by-zero on zero-activity days.
Part B (PostgreSQL)
WITH valid_events AS ( -- identical to Part A
SELECT DISTINCT
e.user_id,
e.event_type,
CAST(e.event_time AS DATE) AS event_date
FROM events e
JOIN sessions s
ON s.session_id = e.session_id
AND s.user_id = e.user_id
AND e.event_time BETWEEN s.session_start AND s.session_end
),
first_dates AS (
SELECT
user_id,
MIN(CASE WHEN event_type = 'login' THEN event_date END) AS first_login_date,
MIN(CASE WHEN event_type = 'purchase' THEN event_date END) AS first_purchase_date
FROM valid_events
GROUP BY user_id
)
SELECT
u.id AS user_id,
f.first_login_date,
f.first_purchase_date,
COALESCE(
f.first_purchase_date BETWEEN f.first_login_date
AND f.first_login_date + INTERVAL '7 days',
FALSE
) AS within_7_days
FROM users u
LEFT JOIN first_dates f ON f.user_id = u.id
ORDER BY u.id;
"Within 7 days inclusive" means the difference is between 0 and 7 days — same-day purchase qualifies. When first_purchase_date precedes first_login_date (data anomaly), the BETWEEN evaluates to FALSE. COALESCE(..., FALSE) handles the case where either date is NULL (user never logged in or never purchased). Starting from users ensures every user appears even with no events.
Expected output:
| user_id | first_login_date | first_purchase_date | within_7_days |
|---|---|---|---|
| 1 | 2025-08-31 | 2025-08-31 | TRUE |
| 2 | 2025-09-01 | 2025-09-01 | TRUE |
| 3 | 2025-08-25 | NULL | FALSE |
Part C (Python / pandas)
import pandas as pd
def _build_valid_events(events_df: pd.DataFrame,
sessions_df: pd.DataFrame) -> pd.DataFrame:
"""
Returns a deduplicated DataFrame of valid events with an added
'event_date' column (UTC calendar day).
Deduplication: rows sharing an event_id are collapsed to one before
the join, so duplicate ingestion does not inflate counts.
Orphaned events: the inner merge on [session_id, user_id] silently
drops any event whose (session_id, user_id) pair has no matching
session row.
Out-of-window events: after the merge, rows where event_time falls
outside [session_start, session_end] are filtered out.
Time handling: all timestamp columns are coerced to UTC-aware
Timestamps; event_date is the UTC calendar day (time set to midnight).
"""
ev = (events_df
.drop_duplicates(subset="event_id")
.copy())
ev["event_time"] = pd.to_datetime(ev["event_time"], utc=True)
se = (sessions_df[["session_id", "user_id", "session_start", "session_end"]]
.drop_duplicates(subset="session_id")
.copy())
se["session_start"] = pd.to_datetime(se["session_start"], utc=True)
se["session_end"] = pd.to_datetime(se["session_end"], utc=True)
merged = ev.merge(se, on=["session_id", "user_id"], how="inner")
in_window = (merged["event_time"] >= merged["session_start"]) & \
(merged["event_time"] <= merged["session_end"])
merged = merged[in_window].copy()
merged["event_date"] = merged["event_time"].dt.normalize() # UTC midnight
return merged
def retention_1d(as_of: str = "2025-09-01",
events_df: pd.DataFrame = None,
sessions_df: pd.DataFrame = None) -> float:
"""
Returns the percentage (0–100) of users whose first valid login date
falls in [as_of - 6 days, as_of] and who have any valid event on
exactly first_login_date + 1 calendar day.
Returns float('nan') when the cohort is empty.
as_of boundary: events timestamped after the end of as_of (UTC) are
excluded by filtering event_date <= cutoff before computing any dates,
preventing look-ahead bias.
"""
cutoff = pd.Timestamp(as_of, tz="UTC")
window_start = cutoff - pd.Timedelta(days=6)
valid = _build_valid_events(events_df, sessions_df)
# No look-ahead: ignore anything after the as_of date
valid = valid[valid["event_date"] <= cutoff]
# --- cohort: first login date per user ---
logins = valid[valid["event_type"] == "login"]
cohort = (logins
.groupby("user_id")["event_date"]
.min()
.rename("first_login_date")
.reset_index())
cohort = cohort[
(cohort["first_login_date"] >= window_start) &
(cohort["first_login_date"] <= cutoff)
].copy()
if cohort.empty:
return float("nan")
cohort["target_date"] = cohort["first_login_date"] + pd.Timedelta(days=1)
# --- activity set: distinct (user_id, event_date) pairs ---
active_days = valid[["user_id", "event_date"]].drop_duplicates()
# --- retention check: did the user appear on their target day? ---
merged = cohort.merge(
active_days.rename(columns={"event_date": "target_date"}),
on=["user_id", "target_date"],
how="left",
indicator=True
)
retained = (merged["_merge"] == "both").sum()
return round(100.0 * retained / len(cohort), 2)
Verification with the sample data:
- User 3: first login 2025-08-25, within the
[2025-08-26, 2025-09-01]cohort window? No — excluded. - User 1: first login 2025-08-31; target day 2025-09-01; has a login event on 09-01 → retained.
- User 2: first login 2025-09-01; target day 2025-09-02; no events on 09-02 → not retained.
Result: retention_1d("2025-09-01") == 50.0 (1 out of 2 cohort members).
Common mistakes to avoid
- Joining on only one key. Matching
session_idalone lets a row from a different user sneak through if session IDs are reused across users. - Integer division in SQL.
1 / 2evaluates to0in most SQL dialects; prefix with1.0 *or cast explicitly. - Missing the date spine. Without it, days with zero activity vanish from the output, which breaks downstream charting.
- Look-ahead in retention. Computing first-login dates without capping at
as_ofcan pull in future logins, inflating or distorting the cohort. - Counting events instead of users. Every aggregation here should use
COUNT(DISTINCT user_id), notCOUNT(*).