Gaps & Islands
The ultimate senior analytical challenge: continuous sessionization, consecutive streak detection, and temporal clustering.
Core Learning Objectives
- •Master the date minus row_number technique to identify consecutive day islands
- •Cluster event logs into sessions using LAG() and cumulative conditional sums
- •Merge overlapping time ranges into consolidated shift intervals
Interactive Cheatsheet
PostgreSQL SyntaxWITH grouped_logins AS (
SELECT user_id, login_date,
login_date - (ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY login_date))::INTEGER AS island_id
FROM logins
)
SELECT user_id, MIN(login_date) AS streak_start, MAX(login_date) AS streak_end, COUNT(*) AS streak_days
FROM grouped_logins
GROUP BY user_id, island_id
HAVING COUNT(*) >= 3;Curated Practice Problems (2)
Consecutive Daily Login Streaks (Gaps & Islands)
Meta's Growth team rewards engaged users who achieve consecutive daily active streaks. Write a SQL query using the classic Gaps & Islands technique (subtracting a row number from the login date) to find all users who maintained a streak of at least 3 consecutive calendar days. For each qualifying streak, return: - `user_id` - `streak_start_date` (earliest date in the continuous streak) - `streak_end_date` (latest date in the continuous streak) - `streak_length_days` (total consecutive days) Sort by `streak_length_days` descending, then by `user_id` ascending. Tables: - `user_logins` (`user_id` INT, `login_date` DATE)
Binge-Watching Session Boundary Clustering
Netflix clusters playback events into continuous "Binge Sessions" whenever the gap between sequential episodes is less than or equal to 20 minutes. Write a SQL query using `LAG()` to detect session breaks, compute a running session ID, and aggregate each binge session. Return: - `user_id` - `session_id` (starting from 1 for each user) - `episodes_watched` (count of episodes in the session) - `session_start_time` (first episode start time) Only output sessions with at least 3 episodes. Sort by `episodes_watched` descending. Tables: - `viewing_logs` (`view_id` INT, `user_id` INT, `start_time` TIMESTAMP, `end_time` TIMESTAMP)