AdvancedGaps and islands

Users with a 3-day login streak

Task

logins has one row per user per day they logged in (some days repeat). Return the user_id of every user who logged in on at least 3 consecutive days.

Row order does not matter. Column names do not have to match. SQLite dialect.

Tables

logins

user_id INTEGER, day TEXT

user_idday
12026-05-01
12026-05-02
12026-05-04
12026-05-05
22026-05-01
22026-05-02
22026-05-02
22026-05-03
32026-05-10
32026-05-11
32026-05-12
32026-05-13
42026-05-01
42026-05-03
42026-05-05
Expected output
user_id
2
3
Show solution
SQL
WITH d AS (SELECT DISTINCT user_id, day FROM logins),
g AS (
  SELECT user_id, day,
         julianday(day) - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY day) AS grp
  FROM d
)
SELECT DISTINCT user_id
FROM g
GROUP BY user_id, grp
HAVING COUNT(*) >= 3;

Subtracting a row number from consecutive dates gives the same value for every day in a run, so each streak becomes one group. Deduplicate first: user 2's repeated 2 May shifts the row numbers and splits a real 3-day streak. Counting distinct days is not enough either: user 1 and user 4 have 3+ days but no 3 in a row.

The full explanation, with more examples, is in the question Users with a 3-day login streak.