InterviewPrepKit

Home / SQL / Advanced Patterns

Longest Consecutive Login Streak Per User

hard
Solving tips
  • Gaps-and-islands trick: subtract a per-user ROW_NUMBER() (ordered by date) from the date itself — consecutive dates yield a constant anchor that labels each island.
  • In PostgreSQL `date - integer` returns a date, so the row-number must be cast to int; the resulting anchor is constant only while dates increase by exactly one day.
  • Count rows per (user, island) to get each streak length, then take MAX per user for the longest.

Each row records a day a user logged in (dates are distinct per user). Find each user’s longest run of consecutive calendar days.

Schema

CREATE TABLE logins (
  user_id     INTEGER,
  login_date  DATE
);

Sample data:

user_idlogin_date
12024-01-01
12024-01-02
12024-01-03
12024-01-05
12024-01-06
22024-01-10
22024-01-11
22024-01-13

Task

Return one row per user with columns user_id and longest_streak (the number of days in that user’s longest run of consecutive dates). Order by user_id ascending.

Expected output

user_idlongest_streak
13
22
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.