Consecutive Days, Streaks and Gaps (Gaps and Islands)

SQL Interview Problems: 12 Classic Questions Solved · Windows and Dates · 7 min read · Updated

Gaps and islands

  1. Start with one row per user and day, in date order.
  2. Give each row a number 1, 2, 3 within the user.
  3. Subtract that number of days from the date. Inside a streak the result stays the same.
  4. Group by the user and that value. Each group is one streak.
  5. The first date, last date and row count describe every streak.

"Find users who logged in on three days in a row." "What is each user's longest streak?" "When were the gaps?" These questions have a nickname, gaps and islands. An island is a run of consecutive values, such as the days 5, 6, 7 and 8 of a month. A gap is the missing part between two islands. The problem is popular because the first idea, a loop, does not exist in plain SQL, and the neat solution is a small trick that you can learn in ten minutes. We use the logins table, which has one row for each user and day.

A simple version first: two days in a row

If you only need two consecutive days, a self join is enough. Join the table to itself where the second login is exactly one day after the first.

SELECT DISTINCT a.user_id
FROM logins a
JOIN logins b
  ON b.user_id = a.user_id
 AND b.login_date = date(a.login_date, '+1 day')
ORDER BY a.user_id;
user_id
1
2

Users 1 and 2 both logged in on two days in a row. User 3 logged in once. For three or more days in a row this approach needs one more join for each extra day, which gets ugly. That is when you use the trick below.

The trick: date minus row number

Number each user's login days 1, 2, 3 and so on, in date order. Then subtract that number 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 a day is skipped, the date jumps by two but the row number only by one, so the difference changes. Rows with the same difference belong to the same island.

SELECT login_date,
       ROW_NUMBER() OVER (ORDER BY login_date) AS rn,
       date(login_date, '-' || ROW_NUMBER() OVER (ORDER BY login_date) || ' days') AS grp
FROM logins
WHERE user_id = 1
ORDER BY login_date;
login_date | rn | grp
2024-03-01 | 1  | 2024-02-29
2024-03-02 | 2  | 2024-02-29
2024-03-03 | 3  | 2024-02-29
2024-03-05 | 4  | 2024-03-01
2024-03-06 | 5  | 2024-03-01
2024-03-07 | 6  | 2024-03-01
2024-03-08 | 7  | 2024-03-01
2024-03-10 | 8  | 2024-03-02

Look at the grp column for user 1. The first three days all show 2024-02-29. After the missing 4th of March, the value changes to 2024-03-01 for the next four days, and changes again after the missing 9th. The value itself means nothing. It is only a label that is equal for days that belong together.

Turn the labels into streaks

Now group by user and by that label. The first date, the last date and the number of rows in each group describe the streak.

WITH g AS (
  SELECT user_id, login_date,
         date(login_date, '-' || ROW_NUMBER() OVER (
           PARTITION BY user_id ORDER BY login_date
         ) || ' days') AS grp
  FROM logins
)
SELECT user_id,
       MIN(login_date) AS streak_start,
       MAX(login_date) AS streak_end,
       COUNT(*) AS days
FROM g
GROUP BY user_id, grp
ORDER BY user_id, streak_start;
user_id | streak_start | streak_end | days
1       | 2024-03-01   | 2024-03-03 | 3
1       | 2024-03-05   | 2024-03-08 | 4
1       | 2024-03-10   | 2024-03-10 | 1
2       | 2024-03-01   | 2024-03-02 | 2
2       | 2024-03-04   | 2024-03-04 | 1
3       | 2024-03-05   | 2024-03-05 | 1

User 1 had streaks of 3, 4 and 1 days. User 2 had a streak of 2 days and then a single day. User 3 logged in once. This table answers "who has at least a three-day streak" by adding HAVING COUNT(*) >= 3.

The longest streak for each user

WITH g AS (
  SELECT user_id, login_date,
         date(login_date, '-' || ROW_NUMBER() OVER (
           PARTITION BY user_id ORDER BY login_date
         ) || ' days') AS grp
  FROM logins
),
streaks AS (
  SELECT user_id, COUNT(*) AS days
  FROM g
  GROUP BY user_id, grp
)
SELECT user_id, MAX(days) AS longest_streak
FROM streaks
GROUP BY user_id
ORDER BY user_id;
user_id | longest_streak
1       | 4
2       | 2
3       | 1

We put the streak calculation in a WITH query and then take the maximum per user. User 1's longest streak is 4 days. Notice the small dependency: the trick needs one row per user per day. If a user can log in twice on the same day, first reduce the data with SELECT DISTINCT user_id, login_date, or the row numbers will be wrong.

The gaps

To list the gaps instead, look at each login and the next one with LEAD. When the difference is more than one day, the days in between are missing.

WITH x AS (
  SELECT login_date AS last_seen,
         LEAD(login_date) OVER (ORDER BY login_date) AS next_login
  FROM logins
  WHERE user_id = 1
)
SELECT last_seen, next_login,
       CAST(julianday(next_login) - julianday(last_seen) AS INTEGER) - 1 AS days_missed
FROM x
WHERE julianday(next_login) - julianday(last_seen) > 1;
last_seen  | next_login | days_missed
2024-03-03 | 2024-03-05 | 1
2024-03-08 | 2024-03-10 | 1

User 1 was away for one day after the 3rd, and one day after the 8th. The same idea finds missing invoice numbers, missing order ids, or hours with no data from a sensor.

Common mistakes

  • Forgetting PARTITION BY user_id, so the row numbers run across all users.
  • Duplicate rows for the same day, which break the numbering.
  • Ordering by something other than the date.
  • Saying the grouping label has a meaning. It is only a way to make equal values for rows in the same streak.

Your task

  1. Find the users who have a streak of at least three days.
  2. Find the date on which each user's longest streak started.
  3. List the users who logged in on March 5th and also on March 6th.
  4. Find the first day after each gap, for user 1.

How to check it worked

  • User 1 has three streaks: 3, 4 and 1 days.
  • Only user 1 has a streak of three or more days.
  • The gaps query returns two rows for user 1.

Frequently asked questions

Why does subtracting the row number work?

In a run of consecutive days the date and the row number both grow by one each row, so their difference is constant. A skipped day makes the date grow faster, and the difference changes.

What if the same user logs in twice on one day?

Reduce the data to one row per user and day first with SELECT DISTINCT, or the row numbers no longer match the days.

Can I solve this with LAG instead?

Yes. Use LAG to flag where a new streak starts, then a running sum of those flags gives a streak number. The row-number trick is shorter, and the LAG way is easier to explain.