Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

From logins(user_id, login_at), find users who logged in on at least 3 consecutive days using LAG or a related technique.

First we reduce the data to one row per user and day with SELECT DISTINCT user_id, login_at::date. Then the gaps-and-islands trick subtracts a ROW_NUMBER from each date: within a run of consecutive days the result is constant, so grouping by user and that key and keeping groups with COUNT(*) >= 3 finds the streaks. With LAG, a user qualifies when some day minus LAG(d, 2) over the same ordering is exactly 2 days, and in both cases we convert login_at to the user's time zone before taking the date.

Background to this question

Streak questions come up in every product with engagement features: three days in a row unlocks a badge, seven days triggers a reward, a broken streak sends a reminder. In SQL they are a classic example of the gaps-and-islands problem, finding runs of consecutive values, and they show whether we can think in sets instead of loops. In this answer, we will clean the input to one row per day, solve the problem with LAG, solve it again with the gaps-and-islands technique (which also gives the length of each streak), trace both on sample data, and deal with the time zone detail that quietly breaks streaks.

1One Row per User and Day

The logins table has one row per login, and an active user may log in five times a day. Consecutive days are about dates, not logins, so we first reduce the data to distinct (user_id, day) pairs. Without this step, two logins on the same day would look like two separate days to the logic that follows.

SQL
-- logins (user_id, login_at timestamptz)
-- 1: Jun 1 09:00, Jun 1 18:00, Jun 2 08:30, Jun 3 07:45, Jun 5 10:00
-- 2: Jun 1 12:00, Jun 3 12:00, Jun 4 12:00
SELECT DISTINCT user_id, login_at::date AS d
FROM logins;
-- 1 | 2025-06-01
-- 1 | 2025-06-02
-- 1 | 2025-06-03
-- 1 | 2025-06-05
-- 2 | 2025-06-01
-- 2 | 2025-06-03
-- 2 | 2025-06-04

User 1 has a streak of three days (1, 2 and 3 June) and then a single day. User 2 has a two-day streak at most. So the answer we expect is user 1 only.

2Solution 1: Comparing With LAG

LAG(x, n) is a window function that returns the value of x from n rows earlier in the window's order. Ordering each user's distinct days by date, LAG(d, 2) is the day two rows back. Since the days are distinct and increasing, if that day is exactly two days earlier, the three rows must be three consecutive dates; any gap would make the difference larger.

SQL
WITH days AS (
SELECT DISTINCT user_id, login_at::date AS d FROM logins
)
SELECT DISTINCT user_id
FROM (
SELECT user_id, d,
d - LAG(d, 2) OVER (PARTITION BY user_id ORDER BY d) AS diff -- date minus date = integer days
FROM days
) t
WHERE diff = 2;
-- 1
-- inner rows for user 1: (Jun 1, NULL) (Jun 2, NULL) (Jun 3, 2) (Jun 5, 3)

Notice that the first two rows of each user have no row two back, so LAG returns NULL and they never match. This solution is short and easy to explain. Its limit is that it answers only 'at least three in a row'; if the product asks for the longest streak, or for every streak with its dates, we need the second technique.

3Solution 2: Gaps and Islands

The gaps-and-islands idea is a neat piece of arithmetic. Number each user's days in order with ROW_NUMBER: 1, 2, 3, and so on. Then subtract that number, as days, from the date. Inside a run of consecutive days, the date goes up by one and the row number goes up by one, so the difference stays the same. When there is a gap, the date jumps by more than one while the row number still goes up by one, so the difference changes. That constant difference is a label for the island, the run of consecutive days.

SQL
WITH days AS (
SELECT DISTINCT user_id, login_at::date AS d FROM logins
), islands AS (
SELECT user_id, d,
d - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d))::int AS grp -- date minus integer = date
FROM days
)
SELECT user_id, min(d) AS streak_start, max(d) AS streak_end, count(*) AS days
FROM islands
GROUP BY user_id, grp
HAVING count(*) >= 3;
-- 1 | 2025-06-01 | 2025-06-03 | 3
Gaps and islands for user 1
Day dROW_NUMBERd minus row numberIsland
2025-06-0112025-05-31A
2025-06-0222025-05-31A
2025-06-0332025-05-31A
2025-06-0542025-06-01B
Within a run of consecutive days the difference is constant; a gap changes it.

The same idea is often written as d - ROW_NUMBER() OVER (...) * interval '1 day', which gives a timestamp instead of a date; both work as a group key in PostgreSQL. In MySQL 8 the equivalent is DATE_SUB(d, INTERVAL ROW_NUMBER() OVER (...) DAY).

4Why the Gaps-and-Islands Version Is More Useful

Because it groups each streak into one row, we get the start, the end and the length for free. 'Longest streak per user' becomes SELECT user_id, max(days) over the grouped result. 'Current streak' becomes the island whose streak_end is today or yesterday. A badge rule for seven days needs only HAVING count(*) >= 7.

It also performs well: one sort of the distinct days per user for the window, then a group by. An index on logins (user_id, login_at) helps the DISTINCT step, and for a big table we would restrict to a time window, for example the last 60 days, before doing anything else.

5The Time Zone Detail

login_at is usually stored as a timestamptz, a point in time, and login_at::date takes the date in the session's time zone, often UTC. That is not the user's calendar. A user in California who logs in at 08:00 local time on 1 June, at 20:00 on 2 June and at 09:00 on 3 June has three consecutive days in their own calendar. In UTC those logins are 15:00 on 1 June, 03:00 on 3 June and 16:00 on 3 June, so the distinct UTC dates are 1 June and 3 June, and the streak disappears. The user sees a streak in their own calendar, so the product must count days the same way.

SQL
-- users (id, tz) with tz like 'America/Los_Angeles' or 'Asia/Kolkata'
SELECT DISTINCT l.user_id, (l.login_at AT TIME ZONE u.tz)::date AS d
FROM logins l
JOIN users u ON u.id = l.user_id;

AT TIME ZONE with a zone name converts the instant to that zone's local wall-clock time, and taking the date of that gives the user's own calendar day. Using zone names rather than fixed offsets also gets daylight saving changes right.

6Follow-up questions

How would you find each user's longest streak?

Use the gaps-and-islands query, keep all islands rather than filtering with HAVING, and take the maximum length per user: SELECT user_id, max(days) FROM (the grouped islands) s GROUP BY user_id. Users with no logins at all will not appear, so join to users if they should show 0.

Could you solve it with a self-join instead of window functions?

Yes: join days a to days b on the same user with b.d = a.d + 1, and to days c with c.d = a.d + 2. Every row that survives is the start of a three-day run. It is easy to read for exactly three days but grows one join per extra day, so a seven-day rule needs six joins. The window solutions scale to any length.

What changes if the rule is 'at least once in each of three consecutive weeks'?

Only the unit. We take date_trunc('week', local time) as the bucket instead of the date, and in the gaps-and-islands step we subtract the row number in weeks, for example week - (rn * interval '1 week'). The same idea works for any regular period.

7Conclusion

In this answer, we found users with logins on at least three consecutive days. We first reduced logins to one row per user and day, then compared each day with LAG(d, 2), where a difference of exactly two days means three consecutive dates, and then used the gaps-and-islands technique, where subtracting ROW_NUMBER from the date gives a constant label for every run of consecutive days. The second approach also gives each streak's start, end and length, and in both the date must be taken in the user's own time zone.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd start by reducing logins to one row per user and day, SELECT DISTINCT user_id and login_at cast to date, because several logins on one day must count as one day.

Then, if they want more

Then there are two ways. The quick one is LAG: order each user's days and compute d minus LAG(d, 2). Since the days are distinct and increasing, a difference of exactly two days means the current day and the two before it are consecutive, so any user with such a row qualifies.

The more general one is gaps and islands: subtract the ROW_NUMBER of each day from the date. Inside a run of consecutive days, both go up by one, so the difference is constant, and a gap changes it.

Grouping by user and that difference gives one row per streak, with min and max date and a count, and HAVING count at least three gives the answer. That version also gives the longest streak or the current streak for free.

The detail I'd raise is time zones: the date should be taken in the user's own zone, with login_at AT TIME ZONE the user's zone, otherwise late evening logins can land on the wrong day and break or invent streaks.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "From logins(user_id, login_at), find users who logged in on at least 3 consecutive days...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/bba25ade4c/