Querydrill

Level 5: Interview classics Exercise 123 of 161 Hard Gaps and islands

Longest streak of active days

An SQL exercise from Querydrill. Solve it with a SQL editor in your browser, checked on the rows it returns and again on changed data, and it is checked the moment you submit.

Try it yourself

Return each user_id with the length of their longest run of consecutive active days. A user who was never active two days in a row has a streak of 1.

events (first 12 of 38 rows)

iduser_ideventevent_time
11visit2025-03-01 09:00:00
21signup2025-03-01 09:05:00
31purchase2025-03-01 09:20:00
42visit2025-03-01 10:00:00
51visit2025-03-01 15:00:00
61visit2025-03-02 10:00:00
73visit2025-03-02 12:00:00
83visit2025-03-02 12:40:00
91visit2025-03-03 08:00:00
101purchase2025-03-03 08:10:00
113signup2025-03-03 09:00:00
122visit2025-03-03 11:00:00

Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.

What this exercise teaches

This is the gaps and islands pattern. With one row per user and day, the day minus its row number is constant within a run and jumps when a day is skipped. Counting rows per user and that constant gives the length of every run, and MAX takes the longest.

A hint if you get stuck

Number each user's active days. Inside a run of consecutive days, day minus row number stays the same.

Background you need

Common mistakes on this exercise

  • Works on events instead of days: two events on the same day break the run.
  • Counts all active days, not the longest run of days in a row.

Each of these returns a result that looks plausible. The checker catches them because it runs your query on changed data as well.

Keep going on the practice page

Your first 8 exercises on Querydrill are free, with no account. The practice page has the full editor, timed mode and all the exercises in order. A free account shows 3 reference solutions a day; Pro unlocks every exercise, every solution, timed mode and the certificate.

Open this exercise

More practice on the same topic

More exercises in Interview classics