Interview Questions/SQL/Longest Consecutive Login Streak per User

Longest Consecutive Login Streak per User

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

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 NameTypeDescription
idINTPrimary key
user_idINTID of the user
login_dateDATEDate of the login event

Database Schema (Inferred)

UserLogins

Column NameExample Value
id1
user_id1
login_date2023-01-01

Example

UserLogins

iduser_idlogin_date
112023-01-01
212023-01-02
312023-01-03
412023-01-05
512023-01-06
622023-01-01
722023-01-02
822023-01-04
932023-03-10

Output

user_idlongest_streak
13
22
31

Explanation:

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.

SQL Editor
Loading...

UserLogins

iduser_idlogin_date
112023-01-01
212023-01-02
312023-01-03
412023-01-05
512023-01-06
622023-01-01
722023-01-02
822023-01-04
932023-03-10

Output

user_idlongest_streak
13
22
31