In short
'Find each user's longest login streak' sounds hard until you learn one trick. Once you have it, a whole family of interview questions becomes easy.
Gaps and islands problems ask you to find runs of consecutive values, such as login streaks, or the gaps between them. A common solution subtracts ROW_NUMBER() from the date to create a group key for each streak.

Think of it like this
Diyas along the balcony
On Diwali night, a row of diyas lines the balcony. Some stretches glow without a break, then a few have blown out, then another glowing stretch starts. Each unbroken glowing stretch is an island. The dark spots between them are gaps. Gaps and islands questions ask you to find those stretches in dates or numbers.
Watch it happen
Priya's login days in November
1/5Six distinct login days, sorted. We want each unbroken run of days.
The big ideas
What you need to know
Distinct days first
Two logins on the same day would break the trick. Reduce to one row per user per day before numbering.
Value minus ROW_NUMBER
Within a run of consecutive values, value minus row number is constant. That constant is the island's group key.
Then GROUP BY the key
MIN and MAX give each streak's start and end, and COUNT(*) gives its length.
Gaps with LAG
To find gaps instead, compare each date to LAG(date). A difference above 1 day is a gap.
See it in code
Walk through the code
1WITH days AS (2 SELECT DISTINCT user_id, login_at::date AS login_day3 FROM logins4),5grouped AS (6 SELECT user_id,7 login_day,8 login_day - CAST(ROW_NUMBER() OVER (9 PARTITION BY user_id ORDER BY login_day10 ) AS INT) AS streak_key11 FROM days12)13SELECT user_id,14 MIN(login_day) AS streak_start,15 MAX(login_day) AS streak_end,16 COUNT(*) AS streak_days17FROM grouped18GROUP BY user_id, streak_key19HAVING COUNT(*) >= 320ORDER BY streak_days DESC;1/4One row per user per day, so repeat logins on a day don't break the sequence.
PostgreSQL syntax, where date minus integer gives a date. In MySQL use DATE_SUB(login_day, INTERVAL rn DAY), and in SQL Server DATEADD(day, -rn, login_day).
Save yourself the pain
Common mistakes
Oops
Running ROW_NUMBER on raw login timestamps with several logins per day.
Do this instead
Take DISTINCT dates first. Otherwise the row number runs ahead of the date and streaks split.
Oops
Forgetting PARTITION BY user_id.
Do this instead
Without it, one user's numbering continues into the next user's dates and the keys mean nothing.
Your mission
Longest streak per user
Quick check
Why does login_day minus ROW_NUMBER() stay constant inside a streak?
Go deeper
- 1Find each user's longest daily login streak.
- 2Find missing invoice numbers in a sequence.
- 3Explain the ROW_NUMBER subtraction trick in your own words.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.