Scrivio Interview library
CodingIntermediate8 min read · updated 12 November 2026

Table user_login(user_id int, login_at timestamptz), many logins per day. Return for each user every streak of consecutive login days with start_date, end_date and length in days, and the longest streak per user. Work in UTC.

First reduce the logins to one row per user and UTC day, then subtract a per-user ROW_NUMBER from each day: consecutive days produce the same result, so that difference is an island key. Grouping by user and that key gives each streak's start_date, end_date and length, and ranking the streaks per user by length picks the longest one.

Why this question is asked

Streaks are everywhere in product work: daily active users, learning apps that reward seven days in a row, on-call rotations, sensor uptime. The underlying SQL pattern is called gaps and islands, and interviewers like it because a correct answer needs three separate insights: that duplicates must go first, that a simple subtraction turns consecutive values into equal values, and that the day boundary is a business decision rather than a technical detail. In this answer, we will recap what gaps and islands means, reduce the logins to distinct days, build the island key step by step, group the islands into streaks, pick the longest streak per user, and finally see why the DISTINCT step and the time zone matter so much.

1A Quick Recap of Gaps and Islands

Imagine the days on which a user logged in, written on a line in date order. Runs of days with no missing day between them are islands, and the missing days between runs are gaps. A streak in our question is exactly an island: a maximal run of consecutive login days.

The difficulty is that SQL works on sets of rows, and a single row does not know whether it belongs to the same run as the row before it. We need a value that is identical for every row in one island and different between islands. Once we have such a value, an ordinary GROUP BY does the rest. That value is what we will call the island key.

2Reduce Logins to Distinct UTC Days

The table holds one row per login, and a user may log in five times a day. A streak is about days, so we first turn each timestamp into a calendar day and keep each user-day pair only once.

SQL
SELECT DISTINCT user_id,
(login_at AT TIME ZONE 'UTC')::date AS d
FROM user_login;
-- user 1: 2026-10-01 (from two logins), 2026-10-02, 2026-10-03, 2026-10-05, 2026-10-06

login_at is a timestamptz, a point in time. AT TIME ZONE 'UTC' converts it into the wall clock time in UTC, a timestamp without time zone, and the cast to date cuts off the time. Notice that we name the zone explicitly. If we wrote login_at::date instead, PostgreSQL would use the session's TimeZone setting, and the same query would give different streaks on a laptop in Berlin and on a server in UTC.

3Build the Island Key

Now we number each user's days in order with ROW_NUMBER() and subtract that number from the date. In PostgreSQL, a date minus an integer is a date, so the result is again a date. ROW_NUMBER() returns a bigint, so we cast it to int for the subtraction.

SQL
WITH days AS (
SELECT DISTINCT user_id, (login_at AT TIME ZONE 'UTC')::date AS d
FROM user_login
)
SELECT user_id, d,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d) AS rn,
d - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d))::int AS grp
FROM days;
-- 1 | 2026-10-01 | 1 | 2026-09-30
-- 1 | 2026-10-02 | 2 | 2026-09-30
-- 1 | 2026-10-03 | 3 | 2026-09-30
-- 1 | 2026-10-05 | 4 | 2026-10-01
-- 1 | 2026-10-06 | 5 | 2026-10-01
Island key for user 1
Day dRow numberd - rn (key)
2026-10-0112026-09-30
2026-10-0222026-09-30
2026-10-0332026-09-30
2026-10-0542026-10-01
2026-10-0652026-10-01
The missing 2026-10-04 makes the key jump, which starts a new island.

The reason this works is simple arithmetic. Inside an island, each next row is one day later and also has a row number one higher, so the two increases cancel and the difference stays constant. When a gap appears, the date jumps by more than one while the row number still grows by one, so the difference moves to a new value and stays there for the next island. The key itself is a meaningless date; we only care that it is equal within an island.

MySQL has no date minus integer operator, so there we write DATE_SUB(d, INTERVAL rn DAY) with rn computed in an inner query. The idea is identical.

4Group the Islands Into Streaks

With the key in place, every streak is just a group. MIN gives the first day, MAX the last day, and COUNT the number of days, which equals the length because there are no duplicate days left.

SQL
WITH days AS (
SELECT DISTINCT user_id, (login_at AT TIME ZONE 'UTC')::date AS d
FROM user_login
), keyed AS (
SELECT user_id, d,
d - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY d))::int AS grp
FROM days
)
SELECT user_id, MIN(d) AS start_date, MAX(d) AS end_date, COUNT(*) AS days
FROM keyed
GROUP BY user_id, grp
ORDER BY user_id, start_date;
-- 1 | 2026-10-01 | 2026-10-03 | 3
-- 1 | 2026-10-05 | 2026-10-06 | 2

Notice that end_date - start_date + 1 would give the same length here. Both are fine, and having both is a cheap self-check while testing.

5Pick the Longest Streak per User

For the longest streak we rank each user's streaks by length, longest first, and keep rank 1. We add end_date DESC as a tie-breaker so that, when two streaks are equally long, we deterministically keep the most recent one.

SQL
-- streaks is the query from step 3, wrapped as a CTE
SELECT user_id, start_date, end_date, days
FROM (
SELECT s.*, ROW_NUMBER() OVER (PARTITION BY user_id
ORDER BY days DESC, end_date DESC) AS r
FROM streaks s
) t
WHERE r = 1;
-- 1 | 2026-10-01 | 2026-10-03 | 3
-- PostgreSQL shortcut with DISTINCT ON
SELECT DISTINCT ON (user_id) user_id, start_date, end_date, days
FROM streaks
ORDER BY user_id, days DESC, end_date DESC;
-- 1 | 2026-10-01 | 2026-10-03 | 3

DISTINCT ON keeps the first row of each user_id according to the ORDER BY, so the ORDER BY must start with the DISTINCT ON column. If the product wants every streak that ties for the longest, we would use RANK() instead of ROW_NUMBER() and keep all rows with rank 1.

6Why the DISTINCT Step and the Time Zone Matter

Here is the broken version, without DISTINCT. User 1 logged in twice on 2026-10-01.

SQL
-- days without DISTINCT: 10-01, 10-01, 10-02, 10-03
-- rn: 1, 2, 3, 4
-- d - rn: 09-30, 09-29, 09-29, 09-29
-- result: two streaks (10-01 alone, and 10-01..10-03 with COUNT 3) instead of one

The second login on the same day raises the row number without moving the date, so the key shifts by one and the arithmetic falls apart. That is why the reduction to distinct days is not an optimisation but a requirement.

The time zone matters in a quieter way. A login at 23:30 in New York is already the next day in UTC. The question says to work in UTC, but in a real product we would confirm with the product owner whose day counts: UTC, the user's own zone, or the company's zone. Changing it changes the streaks, and users notice when a streak they believe they kept is broken.

7Follow-up questions

How would you allow one missed day inside a streak?

The subtraction trick only handles strict consecutiveness, so we switch to the session pattern. On the distinct days we compute the previous day with LAG(d) OVER (PARTITION BY user_id ORDER BY d), mark a new streak when the previous day is NULL or d - prev_d > 2, and turn those marks into streak numbers with a running SUM over the same window. A gap of exactly two days, one missed day, then stays inside the streak. We must also decide what length means now: the number of login days from COUNT(*) or the calendar span from end_date - start_date + 1, and agree that with the product owner.

Why not use a self join on d = d + 1 instead?

A self join can tell us whether a given day has a neighbour, but it cannot tell us how long the run is without joining again for every possible length. The window function approach handles any length in one pass and is easier to read.

How would this perform on a large login table?

The distinct step and the window both sort by user and day, so an index on (user_id, login_at) helps, and for daily dashboards we would maintain a user_day table with one row per active day instead of recalculating from raw logins every time.

8Conclusion

In this answer, we turned many logins into one row per user and UTC day, used the difference between the day and its row number as an island key, grouped by that key to get start_date, end_date and length, and picked the longest streak with ROW_NUMBER or DISTINCT ON. We also saw that skipping DISTINCT breaks the arithmetic and that the day boundary is a business decision.

What to say in the interviewAbout 90 seconds aloud

Open with

I would solve this as a gaps and islands problem. First I reduce the raw logins to distinct user and day pairs, converting with login_at AT TIME ZONE 'UTC' and casting to date, because a streak is about days and the time zone decides where a day starts.

Then, if they want more

That DISTINCT is essential: two logins on one day would raise the row number without moving the date and split a streak. Then I compute ROW_NUMBER over each user's days ordered by date and subtract it from the date.

Inside a run of consecutive days, both values grow by one at each step, so the difference stays constant; after a gap it jumps to a new value. That difference is my island key. Grouping by user and key, MIN of the day is the start date, MAX is the end date and COUNT is the length.

For the longest streak per user, I rank the streaks with ROW_NUMBER partitioned by user, ordered by length descending and end date descending as a tie-breaker, and keep rank one; in PostgreSQL DISTINCT ON does the same more briefly. In MySQL the subtraction is DATE_SUB with an interval of rn days.

Finally, I would confirm with the product owner which time zone defines a day, because a login near midnight lands on different days in UTC and in the user's zone.

About this answer

Last updated
12 November 2026
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 "Table user_login(user_id int, login_at timestamptz), many logins per day. Return for...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/663da750dd/