SQL Window Functions: Streaks, Daily Metrics, and Inactivity Gaps
SQL & DataModel answerLast updated
Use window functions to detect consecutive-day activity streaks, compute rolling DAU and revenue metrics, and identify post-order inactivity gaps across three related tables.
Assume today is 2025-09-01. All queries must be written in standard SQL (PostgreSQL dialect). You may use CTEs and window functions freely, but no procedural loops and no correlated subqueries.
Schema
users(user_id INT, signup_date DATE)
events(user_id INT, event_date DATE, event_name TEXT) -- one row per user per day per event type
orders(order_id INT, user_id INT, order_date DATE, amount DECIMAL(8,2))
Sample Data
users
| user_id | signup_date |
|---|---|
| 1 | 2025-08-20 |
| 2 | 2025-08-22 |
| 3 | 2025-08-25 |
events
| user_id | event_date | event_name |
|---|---|---|
| 1 | 2025-08-29 | login |
| 1 | 2025-08-30 | login |
| 1 | 2025-09-01 | login |
| 2 | 2025-08-26 | login |
| 2 | 2025-08-28 | login |
| 2 | 2025-08-29 | login |
| 2 | 2025-09-01 | login |
| 3 | 2025-08-25 | login |
| 3 | 2025-08-26 | login |
| 3 | 2025-08-27 | login |
| 3 | 2025-09-01 | login |
orders
| order_id | user_id | order_date | amount |
|---|---|---|---|
| 10 | 1 | 2025-08-30 | 20.00 |
| 11 | 2 | 2025-08-27 | 15.00 |
| 12 | 2 | 2025-09-01 | 30.00 |
| 13 | 3 | 2025-08-26 | 12.00 |
Tasks
Part A — First qualifying 3-day streak per user
A "3-day consecutive activity streak" means a user had at least one event on three calendar days in a row. Find each user's first such streak whose end date falls in 2025-08-26 through 2025-09-01 inclusive.
Output columns: user_id, streak_start_date, streak_end_date.
Constraint: solve using window functions and date arithmetic only — no self-joins against a dates table.
Part B — Per-day metrics for 2025-08-26 through 2025-09-01
For every calendar day d in that range, return:
DAU— count of distinct users with at least one event ondrevenue_d— total order amount ford(0 if no orders)rolling_7d_dau_avg— trailing 7-day average of DAU ending ond, rounded to 4 decimal placesrevenue_per_active_user—revenue_d / DAUrounded to 4 decimal places;NULLwhen DAU is 0
Days with no events must still appear in the result with DAU = 0.
Part C — Earliest post-order inactivity gap per user
A user "triggers" this flag when they placed an order on some date t and had no events at all for a strict 10-day window immediately after t, but then did have an event on some later date u.
Return only the earliest such gap per user.
Output columns: user_id, last_order_date (= t), gap_days, first_post_gap_event_date (= u).
Hints
Hint 1
Part A: Before applying LAG, collapse events to one row per (user_id, event_date). With fully deduplicated dates, if the active date two positions back equals the current date minus 2, all three intermediate dates must be filled in — that's your streak. Filter streak ends to the target window after the window function runs, not before, or you'll cut off streaks that start before 08-26.
Hint 2
Part B: Build a date spine that starts 6 days before your output window begins. Without it, the 7-day trailing average on 08-26 only sees one day instead of seven. Join aggregated events and orders separately to the spine using LEFT JOIN, then apply AVG(...) OVER (ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). Apply the output-window filter in the outermost SELECT, after the rolling window is computed…
Hint 3
Part C: For each user, find their last order date and the date of their next event after that order. The gap is (next_event_date - last_order_date - 1). Use LEAD or a ranked subquery to get the first event after each order date, then filter to gaps >= 10 and pick the earliest one per user with ROW_NUMBER().
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Common Mistakes
All three parts share the same structure: reduce raw rows to one row per entity per day, then use a window function to compare each row with its neighbors. The most frequent mistakes are (1) forgetting to deduplicate before windowing, (2) filtering the date range too early and pruning rows that a window function still needs, and (3) joining aggregates directly to each other instead of to a spine, which fans out rows.
Part A: First 3-Day Consecutive Streak per User
Idea
Deduplicate events to distinct (user_id, event_date) pairs. For each row, LAG(d, 2) returns the active date two rows earlier in that user's sorted sequence. Because dates within a user are now strictly increasing, if that lagged value equals d - 2, the only date that could sit between them is d - 1 — meaning all three days are covered. That's a streak end.
Filter streak ends to the target window after computing LAG. User 3's streak spans 08-25 → 08-27: the start is outside the window but the end is inside, so the rows from 08-25 and 08-26 must be present when LAG runs.
WITH active_days AS (
SELECT DISTINCT user_id, event_date AS d
FROM events
),
lagged AS (
SELECT
user_id,
d,
LAG(d, 2) OVER (PARTITION BY user_id ORDER BY d) AS two_back
FROM active_days
),
streak_ends AS (
SELECT
user_id,
d - INTERVAL '2 days' AS streak_start_date,
d AS streak_end_date,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d) AS rn
FROM lagged
WHERE two_back = d - INTERVAL '2 days'
AND d BETWEEN DATE '2025-08-26' AND DATE '2025-09-01'
)
SELECT user_id, streak_start_date, streak_end_date
FROM streak_ends
WHERE rn = 1
ORDER BY user_id;
Expected result: only user 3 qualifies — (3, 2025-08-25, 2025-08-27).
- User 1's active days are 08-29, 08-30, 09-01 — a gap between 08-30 and 09-01 breaks the run.
- User 2's active days are 08-26, 08-28, 08-29, 09-01 — the gap between 08-26 and 08-28 means no 3-day run exists.
Alternative: if the interviewer wants maximal islands rather than the first 3-day run, the standard d - ROW_NUMBER() trick assigns a constant group key to each contiguous island. Worth mentioning that you'd clarify the definition.
Part B: Daily DAU, Revenue, Rolling Average, Revenue per User
Idea
Build a dense date spine starting 6 days before the output window (i.e., from 08-20) so that the 7-day trailing average on 08-26 sees a full 7 rows. Aggregate events and orders separately, then LEFT JOIN both to the spine. Joining aggregates to each other first would create a Cartesian product on multi-event days.
WITH spine AS (
SELECT generate_series(
DATE '2025-08-26' - 6,
DATE '2025-09-01',
INTERVAL '1 day'
)::date AS day
),
dau_agg AS (
SELECT event_date AS day, COUNT(DISTINCT user_id) AS dau
FROM events
GROUP BY event_date
),
rev_agg AS (
SELECT order_date AS day, SUM(amount) AS revenue
FROM orders
GROUP BY order_date
),
daily AS (
SELECT
s.day,
COALESCE(d.dau, 0) AS dau,
COALESCE(r.revenue, 0) AS revenue_d
FROM spine s
LEFT JOIN dau_agg d USING (day)
LEFT JOIN rev_agg r USING (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 daily
)
SELECT
day,
dau,
revenue_d,
ROUND(rolling_avg::numeric, 4) AS rolling_7d_dau_avg,
ROUND((revenue_d / NULLIF(dau, 0))::numeric, 4) AS revenue_per_active_user
FROM rolled
WHERE day BETWEEN DATE '2025-08-26' AND DATE '2025-09-01'
ORDER BY day;
Key details:
ROWS BETWEEN 6 PRECEDING AND CURRENT ROWgives exactly 7 rows only because the spine has no gaps. If it did, you'd be averaging fewer days silently.- Zero-DAU days contribute 0 to the rolling average rather than being ignored.
NULLIF(dau, 0)converts division-by-zero toNULLcleanly.- The output-range filter lives in the outermost
WHERE, after all window functions have been evaluated.
Part C: Earliest Post-Order Inactivity Gap per User
Idea
For each order, find the first event that occurs strictly after the order date. The gap in days is first_post_order_event - order_date - 1 (subtracting 1 because the order date itself is not an "inactive" day). Keep only gaps ≥ 10, then pick the earliest qualifying gap per user.
WITH user_orders AS (
SELECT DISTINCT user_id, order_date
FROM orders
),
post_order_events AS (
SELECT
o.user_id,
o.order_date,
MIN(e.event_date) AS first_post_event
FROM user_orders o
JOIN events e
ON e.user_id = o.user_id
AND e.event_date > o.order_date
GROUP BY o.user_id, o.order_date
),
gaps AS (
SELECT
user_id,
order_date AS last_order_date,
first_post_event - order_date - 1 AS gap_days,
first_post_event AS first_post_gap_event_date,
ROW_NUMBER() OVER (
PARTITION BY user_id
ORDER BY order_date
) AS rn
FROM post_order_events
WHERE first_post_event - order_date - 1 >= 10
)
SELECT user_id, last_order_date, gap_days, first_post_gap_event_date
FROM gaps
WHERE rn = 1
ORDER BY user_id;
Trade-off note: this solution uses a non-correlated JOIN rather than LEAD, which is fine when the number of orders per user is small. With very large tables, a LEAD approach over a merged timeline of orders and events can be more efficient since it avoids the JOIN entirely — worth mentioning if the interviewer asks about scale.
Complexity
All three queries are O(N log N) due to window function sorting, where N is the number of rows in the relevant table. No query does a full cross join; the spine in Part B is bounded by a fixed 37-day range.