Longest Consecutive Login Streak per User
Preview mode. Log in to edit, run, submit, and save progress.
Longest Consecutive Login Streak per User
You are given a table of user login events. A user may log in multiple times on the same day. Write a SQL query to find the longest consecutive-day login streak for each user. Two logins are consecutive if one occurs exactly the day after the other. Duplicate login dates count as a single active day. Return one row per user with their longest streak length, ordered by user_id. Table: UserLogins
| Column Name | Type | Description |
|---|---|---|
| id | INT | Primary key |
| user_id | INT | ID of the user |
| login_date | DATE | Date of the login event |
Examples
User 1 has streaks of 3 (Jan 1-3) and 2 (Jan 5-6); longest = 3. User 2 has a streak of 2 (Jan 1-2) then a gap; longest = 2. User 3 logged in once; streak = 1. The island-detection trick: subtract row_number from date to produce a constant group key for each consecutive run.
Approach hint
Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.
Common mistake
Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.