Flagging Heavy VR Headset Users: Streak Detection in SQL
SQL & DataModel answerLast updated
Define a precise rule for excessive headset use, then write SQL that counts flagged users, active users, and the flagged share over a trailing 30-day window.
Scenario
A wellbeing team at a VR hardware company wants to measure how common marathon headset sessions are. Usage is logged in a table named vr_sessions, with one row per session:
| user_id | session_start | session_end | device | event_date |
|---|---|---|---|---|
| 1 | 2024-05-01 10:00:00 | 2024-05-01 12:30:00 | Quest2 | 2024-05-01 |
| 1 | 2024-05-02 09:00:00 | 2024-05-02 13:45:00 | Quest2 | 2024-05-02 |
| 2 | 2024-05-01 18:00:00 | 2024-05-01 18:45:00 | Quest3 | 2024-05-01 |
| 3 | 2024-05-01 20:10:00 | 2024-05-01 22:10:00 | Quest2 | 2024-05-01 |
| 3 | 2024-05-02 20:05:00 | 2024-05-02 22:30:00 | Quest2 | 2024-05-02 |
event_date is the calendar date on which the session began.
Task
- Define the rule. Propose a precise, SQL-expressible definition of an "unhealthy" user. One reasonable example: a user who, within the last 30 days, had a single session longer than 120 minutes on each of at least 3 consecutive calendar days. State every assumption you make (what "continuous" means, strict vs. non-strict thresholds, how midnight-crossing sessions are dated, which days belong to the window).
- Write the query. Using your rule, return one row with:
- (a) the number of unhealthy users,
- (b) the total number of active users (users with at least one session in the window),
- (c) the percentage of active users who are unhealthy.
- Check it against the sample rows above and explain the result.
- Discuss edge cases and how the rule or query would change for them.
Hints
Hint 1
Start by turning each session into a duration in minutes (end minus start), then collapse to one row per user per calendar day, keeping only the days that satisfy your 'heavy' condition.
Hint 2
For consecutive days, subtract a per-user ROW_NUMBER (ordered by date) from the date. Dates in an unbroken run share the same difference, so that value works as a group key; a group with 3 or more rows is a qualifying streak.
Hint 3
Make sure each user-date appears only once before applying the row-number trick, use the same 30-day filter for numerator and denominator, force decimal division, and protect against a zero denominator.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Make the rule precise
Before writing SQL, I would commit to a definition and say it out loud:
A user is unhealthy if, in the last 30 days (today included), there are at least 3 consecutive calendar days on each of which they had at least one single session longer than 120 minutes.
Assumptions worth stating:
- "Continuous" means one session. Ten 15-minute sessions are a different behavior from one 150-minute session. Variants: merge sessions separated by short gaps (say 10 minutes) into one block, or use a daily-total rule such as
SUM(minutes) > 180. - Strictly greater than 120. A session of exactly 120 minutes does not count.
- A session belongs to its start date (
event_date). A 23:00 to 02:00 session counts as 180 minutes on the start day. - Window is
CURRENT_DATE - 29throughCURRENT_DATE, and the whole streak must fall inside it. - Active user means at least one valid session in that same window, so numerator and denominator share one population.
2. Approach
- Compute
minutes = session_end - session_start, dropping null or non-positive durations. - Group by
(user_id, event_date)and keep days whereMAX(minutes) > 120. These are the heavy days, one row per user-day. - Apply gaps and islands:
event_date - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY event_date). Within an unbroken run of dates both quantities rise by 1 per row, so the difference is constant. Any missing date shifts it and begins a new group. - Groups with
COUNT(*) >= 3identify unhealthy users. Count each user once. - The denominator is the distinct users in the filtered session set.
3. SQL (PostgreSQL)
WITH sessions AS (
SELECT
user_id,
event_date,
EXTRACT(EPOCH FROM (session_end - session_start)) / 60.0 AS minutes
FROM vr_sessions
WHERE event_date BETWEEN CURRENT_DATE - 29 AND CURRENT_DATE
AND session_end IS NOT NULL
AND session_end > session_start
),
heavy_days AS (
SELECT user_id, event_date
FROM sessions
GROUP BY user_id, event_date
HAVING MAX(minutes) > 120
),
islands AS (
SELECT
user_id,
event_date,
event_date - CAST(ROW_NUMBER() OVER (
PARTITION BY user_id ORDER BY event_date) AS INT) AS grp
FROM heavy_days
),
unhealthy AS (
SELECT DISTINCT user_id
FROM islands
GROUP BY user_id, grp
HAVING COUNT(*) >= 3
),
active AS (
SELECT DISTINCT user_id FROM sessions
)
SELECT
(SELECT COUNT(*) FROM unhealthy) AS unhealthy_users,
(SELECT COUNT(*) FROM active) AS active_users,
ROUND(100.0 * (SELECT COUNT(*) FROM unhealthy)
/ NULLIF((SELECT COUNT(*) FROM active), 0), 2) AS pct_unhealthy;
A shorter alternative after filtering to heavy days: a user has a 3-day streak if some row satisfies event_date - LAG(event_date, 2) OVER (PARTITION BY user_id ORDER BY event_date) = 2. The islands version is preferable because it generalizes to N days and can report streak lengths.
4. Why it is correct
- Uniqueness first. The row-number trick needs one row per user-date. Grouping in
heavy_daysguarantees this even when a day has several long sessions. - Groups equal runs. Two heavy dates share a
grpvalue exactly when no non-heavy date separates them, soCOUNT(*)is the run length. - No double counting.
DISTINCThandles users with multiple qualifying streaks. - Safe ratio.
100.0avoids integer division;NULLIFavoids divide-by-zero on an empty window. The numerator is a subset of the denominator because both derive from the same filteredsessions.
5. Sanity check on the sample
| User | Day 1 | Day 2 | Heavy days | Unhealthy? |
|---|---|---|---|---|
| 1 | 150 min | 285 min | 2 consecutive | No, fewer than 3 |
| 2 | 45 min | none | 0 | No |
| 3 | 120 min | 145 min | 1 (the 120-minute day fails the strict >) | No |
Result: unhealthy_users = 0, active_users = 3, pct_unhealthy = 0.00. User 3 is the boundary case worth walking through explicitly.
6. Complexity and scale
- Time: O(n log n) in the number of sessions in the window, dominated by the per-user sort for
ROW_NUMBER; aggregations are roughly O(n) with hashing. - Space: O(n) for intermediates.
- At scale: partition the table by date so the 30-day filter prunes data, and maintain a daily rollup (
user_id, date, max_session_minutes) so the streak query scans one row per user-day instead of every session.
7. Edge cases and common mistakes
- Midnight-crossing sessions. Attribute to the start day (as here) or split at midnight. Splitting can turn one long session into two short ones, so pick deliberately and document it.
- Overlapping devices. Two headsets used simultaneously can double count in a daily-total rule; merge overlapping intervals first.
- Fragmented sessions. Crashes or reconnects split one real sitting. Sessionize by starting a new block when
session_start - LAG(session_end) > 10 minutes, then measure per block. - Bad data. Exclude null ends, negative durations, and implausible values (for example over 24 hours).
- Time zones. Define "day" in the user's local time, otherwise late-evening sessions get assigned to the wrong date.
- Window edges. A streak that began before the window only contributes its in-window days; confirm that matches the product intent.
- Typical mistakes: forgetting to deduplicate to one row per user-day before the row-number trick, using
>=when the rule says strictly greater, computing the denominator over a different window than the numerator, and doing integer division so the percentage collapses to 0.