KatInterview

Daily Funnel Metrics and 1-Day Retention in SQL and pandas

SQL & DataModel answer
MediumModel answerSQL & Datasqlpandasfunnel

Last 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:

columndefinition
datethe calendar date
session_usersdistinct users who had a session start on day d
login_usersdistinct users with a valid login event on day d
purchase_usersdistinct users with a valid purchase event on day d
login_to_purchasepurchase_users / login_users as a decimal
session_to_purchasepurchase_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 event
  • first_purchase_date — earliest calendar date of a valid purchase event
  • within_7_days — TRUE if first_purchase_date is between first_login_date and first_login_date + 7 days inclusive; 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:

  1. Build the same valid-event set (matching session window, both join keys) from the DataFrames.
  2. 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).
  3. 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_id rows
  • 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_of boundary

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.