Consecutive Activity Streaks with Window Functions

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

Treat 2025-09-01 as the current date. Given three tables (users, events, and orders), solve the following analytical tasks in standard SQL using window functions and calendar arithmetic only—without procedural loops, correlated subqueries, or date-shifted self-joins:

  1. Task A — Earliest Qualifying 3-Day Activity Streak (graded): An account counts as active on a calendar date whenever at least one row exists in events for that account on that date (any event_name). A 3-day streak consists of three consecutive active calendar dates (d - 2, d - 1, d). For each account, return the qualifying 3-day streak with the earliest streak_end_date lying between 2025-08-26 and 2025-09-01 inclusive, outputting user_id, streak_start_date, and streak_end_date. Exclude accounts that have no qualifying streak.
  2. Task B — Daily Engagement & Revenue Rollup: For every calendar date d from 2025-08-26 through 2025-09-01 inclusive, output day, DAU (count of distinct accounts with an event on d), revenue_d (total orders.amount on order_date = d), rolling_7d_DAU_avg (trailing 7-calendar-day mean of DAU ending on d), and revenue_per_active_user (revenue_d / DAU rounded to 4 decimal places, returning NULL when DAU = 0).
  3. Task C — Post-Order Event Dormancy: Find accounts that placed an order on date t, recorded zero events across at least the next 10 consecutive calendar days immediately after t, and later logged an event on date u. Return only the earliest such occurrence per account with columns user_id, last_order_date (t), gap_days, and first_post_gap_event_date (u).

Automated tests grade Task A: write a single SQL query assigned to QUERY returning user_id, streak_start_date, and streak_end_date in any row order.

Input Schema

users

Column Type Description
user_id INTEGER Unique account identifier.
signup_date DATE Calendar date the account registered.

events

Column Type Description
user_id INTEGER Account that triggered the interaction.
event_date DATE Calendar date of the interaction.
event_name VARCHAR Action label (for example, 'view', 'search', 'checkout').

orders

Column Type Description
order_id INTEGER Unique order identifier.
user_id INTEGER Account that placed the order.
order_date DATE Calendar date of the purchase.
amount DECIMAL(8,2) Monetary value of the purchase.

Examples

Example 1

Input:

users

user_id signup_date
101 '2025-08-18'
102 '2025-08-21'
103 '2025-08-24'
104 '2025-08-24'

events

user_id event_date event_name
101 '2025-08-24' 'view'
101 '2025-08-25' 'search'
101 '2025-08-26' 'view'
101 '2025-08-27' 'checkout'
102 '2025-08-27' 'open'
102 '2025-08-29' 'open'
102 '2025-08-29' 'share'
102 '2025-08-30' 'open'
103 '2025-08-30' 'view'
103 '2025-08-31' 'view'
103 '2025-08-31' 'cart'
103 '2025-09-01' 'checkout'
104 '2025-08-23' 'view'
104 '2025-08-24' 'view'
104 '2025-08-25' 'view'
104 '2025-08-30' 'view'

orders

order_id user_id order_date amount
501 101 '2025-08-27' 45.00
502 102 '2025-08-28' 18.50
503 103 '2025-09-01' 62.00

Output (Task A):

user_id streak_start_date streak_end_date
101 '2025-08-24' '2025-08-26'
103 '2025-08-30' '2025-09-01'

Explanation: - Account 101 is active four days in a row (08-24 through 08-27), creating two 3-day windows ending inside 08-26 .. 09-01: 08-24 .. 08-26 and 08-25 .. 08-27. Only the earliest (08-24 .. 08-26) is returned; streak_start_date is allowed to precede 2025-08-26. - Account 102 has no event on 2025-08-28 (the purchase in orders does not count as an events row, and two events on 08-29 still count as one day), so 102 is omitted. - Account 103 is active across the month boundary 08-30, 08-31, 09-01, returning ('2025-08-30', '2025-09-01'). - Account 104 completed a 3-day streak ending 2025-08-25, which precedes the 2025-08-26 .. 2025-09-01 target window, so 104 is omitted.

Example 2

Input:

users

user_id signup_date
201 '2025-08-25'
202 '2025-08-26'

events

user_id event_date event_name
201 '2025-08-26' 'view'
201 '2025-08-27' 'view'
201 '2025-08-29' 'view'
201 '2025-08-30' 'view'
202 '2025-08-31' 'view'
202 '2025-09-01' 'view'
202 '2025-09-02' 'view'

orders

(empty)

Output (Task A):

(0 rows)

Explanation: Account 201 has two separate 2-day runs broken by 2025-08-28, and Account 202 finishes its 3-day run on 2025-09-02 (after 2025-09-01), so neither qualifies.

Constraints

  • Use window functions and date arithmetic rather than self-joins on dates/events or correlated subqueries.
  • Multiple events rows for the same (user_id, event_date) represent a single active calendar day; ignore rows with event_date IS NULL.
  • Activity in Task A comes strictly from events (never from users or orders).
  • Only streak_end_date is constrained to 2025-08-26 through 2025-09-01 inclusive; streak_start_date (streak_end_date - 2 days) may be 2025-08-24 or 2025-08-25.
  • Return at most one row per user_id (the qualifying 3-day window with the minimum streak_end_date); omit accounts with no qualifying streak. Row order does not matter.

Step-by-step walkthrough

  1. Understand Task A and its boundary rules

    This interview prompt contains three tasks (A, B, and C). Automated tests grade Task A, while Tasks B and C are walked through in full under the follow-up questions in the explanation.

    In Task A, a user is active on a calendar date if they have at least one row in events on that date (regardless of event_name). A 3-day streak means three consecutive active calendar dates: d - 2, d - 1, and d. For each user, we must return user_id, streak_start_date (d - 2), and streak_end_date (d) for the qualifying streak with the earliest end date d inside 2025-08-26 .. 2025-09-01 inclusive, omitting users who have none.

    Pay special attention to two easy-to-miss rules:

    1. Only streak_end_date must fall inside 2025-08-26 .. 2025-09-01. A streak running 2025-08-24, 2025-08-25, 2025-08-26 ends on 2025-08-26, so it qualifies with streak_start_date = '2025-08-24'.
    2. A longer run produces multiple 3-day windows, and we want only the first. If a user is active every day from 2025-08-27 through 2025-09-01, the windows 08-27..08-29, 08-28..08-30, 08-29..08-31, and 08-30..09-01 all qualify; we return only 2025-08-27 .. 2025-08-29.
  2. Why window functions replace self-joins

    Without window functions, checking whether d - 2, d - 1, and d are all active requires joining the activity table to itself twice on shifted dates or running correlated EXISTS subqueries — both explicitly disallowed by the prompt.

    A window function performs a calculation across neighboring rows in a sorted group while keeping every individual row intact (unlike GROUP BY, which collapses rows into one summary row). Once each user's active dates are deduplicated and sorted from earliest to latest, the active dates right before day sit on the rows immediately above day, where LAG can read them in a single pass.

  3. Deduplicate events to one row per user per day

    In events, a user can trigger several different event_name rows on the same calendar day (login, view, purchase). Before calling LAG, we must collapse events to at most one row per (user_id, day) using SELECT DISTINCT.

    Watch how duplicate same-day rows break "look 2 rows back" in both directions if you skip DISTINCT:

    Case 1 — False negative (hides a real streak 08-26 .. 08-28):
      raw rows:  08-26 (login),  08-27 (login),  08-27 (view),  08-28 (click)
                                                 ^-- 2 rows back from 08-28 is 08-27, not 08-26!
    
    Case 2 — False positive (invents a fake streak when 08-27 is missing):
      raw rows:  08-26 (login),  08-28 (login),  08-28 (view)
                                 ^               ^-- 2 rows back from second 08-28 is 08-26!
                                 (08-27 had zero activity!)
    

    Wrapping event_date in DATE(event_date) also strips any timestamp component if present, and WHERE event_date IS NOT NULL drops unparseable NULL rows:

    WITH active_days AS (
        -- Collapse multiple same-day events into one row per (user_id, day)
        SELECT DISTINCT
            user_id,
            DATE(event_date) AS day
        FROM events
        WHERE event_date IS NOT NULL
    ),
    
  4. Key insight: two rows back equals two calendar days back

    Now sort each user's distinct active dates (PARTITION BY user_id ORDER BY day) and peek 2 rows back using LAG(day, 2):

    • When does LAG(day, 2) equal day - 2 days?
    • Because active_days contains distinct calendar dates in strictly increasing order, the row LAG(day, 1) sits strictly between LAG(day, 2) and day:
    Row k - 2 :  2025-08-25   <-- LAG(day, 2) = day - 2 days
    Row k - 1 :  2025-08-26   <-- strictly between Aug 25 and Aug 27, so it MUST be Aug 26!
    Row k     :  2025-08-27   <-- current row (day)
    

    There is only one whole calendar date strictly between day - 2 and day, namely day - 1! So LAG(day, 2) = day - 2 days holds if and only if day - 2, day - 1, and day are all active. We do not even need a separate LAG(day, 1) check. (For a user's first two active rows, LAG(day, 2) returns NULL, which never equals a date.)

    Use real calendar arithmetic — DATE(day, '-2 days') in SQLite (or day - 2 in PostgreSQL) — rather than subtracting day-of-month integers, so streaks crossing month boundaries like 2025-08-30, 2025-08-31, 2025-09-01 work seamlessly:

    with_lag AS (
        -- Look 2 active rows back in chronological order within each user's timeline
        SELECT
            user_id,
            day,
            LAG(day, 2) OVER (PARTITION BY user_id ORDER BY day) AS day_two_rows_back
        FROM active_days
    ),
    
  5. Filter end dates into the window and pick the earliest per user

    Next, filter to qualifying 3-day streaks whose end date day falls inside '2025-08-26' .. '2025-09-01', and number them per user:

    • Why filter dates here instead of in active_days? If we had filtered day >= '2025-08-26' inside active_days, 2025-08-24 and 2025-08-25 would have been deleted before LAG ran, making it impossible to detect streaks like 08-25 .. 08-27!
    • How ROW_NUMBER interacts with WHERE: In SQL execution order, WHERE runs before SELECT window functions. Thus ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) numbers only the qualifying streak rows (1, 2, ...), so WHERE rn = 1 in the outer query selects the earliest qualifying streak for each user.
    streaks AS (
        SELECT
            user_id,
            day_two_rows_back AS streak_start_date,
            day AS streak_end_date,
            -- Number each user's qualifying 3-day windows chronologically so rn = 1 is earliest
            ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS rn
        FROM with_lag
        -- Because active days are distinct and sorted, 2 rows back = 2 calendar days back
        -- guarantees day - 1 was active too; filter the end date after LAG so earlier starts survive
        WHERE day_two_rows_back = DATE(day, '-2 days')
          AND day BETWEEN '2025-08-26' AND '2025-09-01'
    )
    SELECT
        user_id,
        streak_start_date,
        streak_end_date
    FROM streaks
    WHERE rn = 1
    
  6. Trace Example 1 row by row

    Here is every deduplicated (user_id, day) row in with_lag across all four users in Example 1:

    user_id  day         day_two_rows_back  DATE(day, '-2 days')  qualifies?
    -------  ----------  -----------------  --------------------  ------------------------------------------
    101      2025-08-24  NULL               2025-08-22            no (first active row)
    101      2025-08-25  NULL               2025-08-23            no (second active row)
    101      2025-08-26  2025-08-24         2025-08-24            YES -> end 08-26 in window, rn = 1 (kept!)
    101      2025-08-27  2025-08-25         2025-08-25            qualifies, rn = 2 (skipped by rn = 1)
    102      2025-08-27  NULL               2025-08-25            no
    102      2025-08-29  NULL               2025-08-27            no (2 events on 08-29 collapsed to 1 row)
    102      2025-08-30  2025-08-27         2025-08-28            no (08-28 missing; order on 08-28 != event)
    103      2025-08-30  NULL               2025-08-28            no
    103      2025-08-31  NULL               2025-08-29            no (2 events on 08-31 collapsed to 1 row)
    103      2025-09-01  2025-08-30         2025-08-30            YES -> end 09-01 in window, rn = 1 (kept!)
    104      2025-08-23  NULL               2025-08-21            no
    104      2025-08-24  NULL               2025-08-22            no
    104      2025-08-25  2025-08-23         2025-08-23            no (end 08-25 is before 2025-08-26)
    104      2025-08-30  2025-08-24         2025-08-28            no
    

    Notice User 102 placed an order on 2025-08-28, which does not count because Task A defines activity strictly from events, and User 104's streak ended on 2025-08-25 before the target window. Users 101 and 103 qualify, returning (101, '2025-08-24', '2025-08-26') and (103, '2025-08-30', '2025-09-01').

  7. Complete SQL solution (Task A)

    Putting all three CTEs together gives the complete query:

    WITH active_days AS (
        -- Collapse multiple same-day events into one row per (user_id, day)
        SELECT DISTINCT
            user_id,
            DATE(event_date) AS day
        FROM events
        WHERE event_date IS NOT NULL
    ),
    with_lag AS (
        -- Look 2 active rows back in chronological order within each user's timeline
        SELECT
            user_id,
            day,
            LAG(day, 2) OVER (PARTITION BY user_id ORDER BY day) AS day_two_rows_back
        FROM active_days
    ),
    streaks AS (
        SELECT
            user_id,
            day_two_rows_back AS streak_start_date,
            day AS streak_end_date,
            -- Number each user's qualifying 3-day windows chronologically so rn = 1 is earliest
            ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS rn
        FROM with_lag
        -- Because active days are distinct and sorted, 2 rows back = 2 calendar days back
        -- guarantees day - 1 was active too; filter the end date after LAG so earlier starts survive
        WHERE day_two_rows_back = DATE(day, '-2 days')
          AND day BETWEEN '2025-08-26' AND '2025-09-01'
    )
    SELECT
        user_id,
        streak_start_date,
        streak_end_date
    FROM streaks
    WHERE rn = 1
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture circling every day a user logs an event on a desk calendar and writing those circled dates into one sorted list per user, with no duplicate dates. To check whether a date d finishes a 3-day streak (d - 2, d - 1, d), you only need to look two lines up in that sorted list using LAG(day, 2) — a window function (a SQL function that reads neighboring rows in a sorted partition without collapsing rows like GROUP BY). Because every entry in the list is a distinct whole calendar date in strictly ascending order, the entry two lines up can equal d - 2 days only if the entry one line up is squeezed onto d - 1 day.

Without window functions, you would have to join the activity table to itself twice (d, d - 1, d - 2) or run a correlated subquery per row, doing repeated lookups that the prompt explicitly forbids. On the other hand, applying LAG(event_date, 2) directly to the raw events table without deduplicating fails whenever a user triggers multiple events on the same day: two events on d - 1 push d - 2 three rows back (hiding a real streak), while two events on d pull d - 2 into LAG(..., 2) even when d - 1 had zero activity (inventing a fake streak).

Walk through User 101 in Example 1, whose active dates are 2025-08-24, 2025-08-25, 2025-08-26, and 2025-08-27. After SELECT DISTINCT ensures one row per (user_id, day), LAG(day, 2) yields NULL, NULL, 2025-08-24, and 2025-08-25. Both 2025-08-26 (two rows back = 2025-08-24) and 2025-08-27 (two rows back = 2025-08-25) match DATE(day, '-2 days') inside 2025-08-26 .. 2025-09-01, so ROW_NUMBER() assigns rn = 1 to the earlier window and returns (101, '2025-08-24', '2025-08-26') alongside User 103's month-crossing (103, '2025-08-30', '2025-09-01').

Complexity

Let E be the total number of rows in events, and let A (A <= E) be the number of distinct (user_id, day) pairs.

  • Time: Building active_days scans all E rows once and deduplicates them into A pairs in O(E) expected time with hashing (or O(E log E) via sorting). Evaluating LAG(day, 2) in with_lag sorts those A pairs by (user_id, day) in O(A log A) time and walks the sorted rows once; because streaks uses the exact same (user_id, day) ordering for ROW_NUMBER(), the database can stream streaks and the final WHERE rn = 1 filter in O(A) time without re-sorting.
  • Space: The query holds the A deduplicated (user_id, day) rows in memory (or temporary sort storage) for the window partitions, using O(A) space.

Two physical optimizations make this fast on large production tables:

  • Composite index on events(user_id, event_date): Because rows are already stored in (user_id, event_date) order inside the B-tree index, the database can deduplicate active_days and evaluate both OVER (PARTITION BY user_id ORDER BY day) windows in a single ordered index scan with zero explicit sorting.
  • Pre-filtering historical dates: The earliest start date of a streak ending on 2025-08-26 is 2025-08-24, so adding AND event_date >= '2025-08-24' AND event_date < '2025-09-02' inside active_days scans at most 9 days of data while producing the exact same answer.

Edge cases

  • Multiple events on the same day: Collapsed into a single (user_id, day) row by SELECT DISTINCT, preventing LAG(day, 2) from miscounting rows.
  • Streaks that start before 2025-08-26: Allowed as long as streak_end_date falls in 2025-08-26 .. 2025-09-01 (for example, Example 1's 08-24 .. 08-26 for User 101).
  • Streaks longer than 3 consecutive days: A 6-day streak produces four 3-day windows, and ROW_NUMBER() ... WHERE rn = 1 keeps only the earliest qualifying window.
  • Streaks crossing a month or year boundary: 2025-08-30, 2025-08-31, 2025-09-01 is handled accurately because DATE(day, '-2 days') performs true calendar arithmetic.
  • Streaks ending before 2025-08-26 or after 2025-09-01: Excluded by day BETWEEN '2025-08-26' AND '2025-09-01' (such as User 104's 08-23 .. 08-25 run in Example 1).
  • Orders on days without events: Ignored for Task A (User 102 has an order on 08-28 but no event on 08-28, so 08-27, 08-29, 08-30 is not a streak).
  • NULL event dates or empty events table: WHERE event_date IS NOT NULL drops NULL dates cleanly, and an empty table returns zero rows with the expected columns.

Common mistakes

  • Omitting SELECT DISTINCT before LAG: Same-day duplicate events shift row offsets, causing both missed streaks and false-positive streaks across gaps.
  • Filtering event_date >= '2025-08-26' in the first CTE: Deletes 2025-08-24 and 2025-08-25 before LAG runs, missing valid streaks that started before 08-26 and ended on 08-26 or 08-27.
  • Checking only LAG(day, 1) = DATE(day, '-1 day'): Detects 2-day streaks rather than 3-day streaks.
  • Subtracting day-of-month integers (CAST(STRFTIME('%d', day) AS INT)): Fails across month boundaries (1 - 30 = -29 between August 30 and September 1).
  • Forgetting ROW_NUMBER (or using MIN(streak_start_date) without pairing it cleanly): Returns multiple rows for users who stay active for 4+ days in a row.

Follow-up questions

  • How would you write Task B to compute daily DAU, revenue_d, a 7-day trailing DAU average, and revenue_per_active_user across 2025-08-26 through 2025-09-01? First generate a date spine (a continuous calendar table with one row per calendar date, starting 6 days early on 2025-08-20 so 2025-08-26 has a full 7-day trailing history), because ROWS BETWEEN 6 PRECEDING AND CURRENT ROW counts physical rows and would silently span more than 7 calendar days if zero-activity dates were missing! Then LEFT JOIN pre-aggregated daily DAU and daily order revenue, use COALESCE(..., 0) for quiet days, and use NULLIF(dau, 0) so zero-DAU days (like 2025-08-28 in Example 1, where User 102 placed an order of 18.50 with zero events) return NULL instead of dividing by zero:

sql WITH RECURSIVE calendar(day) AS ( SELECT '2025-08-20' UNION ALL SELECT DATE(day, '+1 day') FROM calendar WHERE day < '2025-09-01' ), daily_dau AS ( SELECT DATE(event_date) AS day, COUNT(DISTINCT user_id) AS dau FROM events WHERE event_date IS NOT NULL GROUP BY DATE(event_date) ), daily_revenue AS ( SELECT DATE(order_date) AS day, SUM(amount) AS revenue_d FROM orders WHERE order_date IS NOT NULL GROUP BY DATE(order_date) ), per_day AS ( SELECT c.day, COALESCE(d.dau, 0) AS dau, COALESCE(r.revenue_d, 0) AS revenue_d FROM calendar AS c LEFT JOIN daily_dau AS d ON d.day = c.day LEFT JOIN daily_revenue AS r ON r.day = c.day ), rolled AS ( SELECT day, dau, revenue_d, AVG(dau) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rolling_avg FROM per_day ) SELECT day, dau AS DAU, revenue_d, ROUND(rolling_avg, 4) AS rolling_7d_DAU_avg, ROUND(1.0 * revenue_d / NULLIF(dau, 0), 4) AS revenue_per_active_user FROM rolled WHERE day BETWEEN '2025-08-26' AND '2025-09-01' ORDER BY day

  • How can you solve Task C—finding each user's earliest order followed immediately by at least 10 event-free calendar days and a subsequent event—using window functions only? Union distinct event days (is_order = 0) and order days (is_order = 1) into a single chronological timeline per user, ordering is_order = 0 before is_order = 1 on the same date so an event on order date t itself sits before the order row and does not count as post-order activity. Then a forward-looking window MIN(CASE WHEN is_order = 0 THEN day END) OVER (PARTITION BY user_id ORDER BY day, is_order ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) finds the very next event date u > t without a correlated subquery; requiring u - t - 1 >= 10 enforces at least 10 event-free calendar days t + 1 .. t + 10 strictly between t and u (note whether your interviewer defines gap_days as the u - t - 1 inactive days or u - t elapsed days):

sql WITH timeline AS ( SELECT user_id, DATE(event_date) AS day, 0 AS is_order FROM events WHERE event_date IS NOT NULL UNION SELECT user_id, DATE(order_date) AS day, 1 AS is_order FROM orders WHERE order_date IS NOT NULL ), with_next_event AS ( SELECT user_id, day, is_order, MIN(CASE WHEN is_order = 0 THEN day END) OVER ( PARTITION BY user_id ORDER BY day, is_order ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING ) AS next_event_day FROM timeline ), gaps AS ( SELECT user_id, day AS last_order_date, CAST(JULIANDAY(next_event_day) - JULIANDAY(day) - 1 AS INTEGER) AS gap_days, next_event_day AS first_post_gap_event_date, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS rn FROM with_next_event WHERE is_order = 1 AND next_event_day IS NOT NULL AND JULIANDAY(next_event_day) - JULIANDAY(day) - 1 >= 10 ) SELECT user_id, last_order_date, gap_days, first_post_gap_event_date FROM gaps WHERE rn = 1

  • How would you adapt the streak logic to return full unbroken consecutive-day runs of arbitrary length instead of fixed 3-day windows? That is the classic gap-and-island problem (grouping consecutive runs of dates into unbroken "islands" separated by missing-date "gaps"). Inside any unbroken streak of consecutive calendar days, both day and ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) advance by +1 on every row, so their difference day - row_number stays constant across the entire streak and jumps to a new date right after every gap! Grouping by (user_id, island_key) gives each full streak's MIN(day), MAX(day), and COUNT(*) length:

sql WITH active_days AS ( SELECT DISTINCT user_id, DATE(event_date) AS day FROM events WHERE event_date IS NOT NULL ), grouped AS ( SELECT user_id, day, DATE(day, '-' || ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) || ' days') AS island_key FROM active_days ) SELECT user_id, MIN(day) AS streak_start_date, MAX(day) AS streak_end_date, COUNT(*) AS streak_days FROM grouped GROUP BY user_id, island_key HAVING COUNT(*) >= 3

Follow-up questions

Similar questions

More Flatiron Health interview questions

All 3 Flatiron Health questions →