Reading history

Gaps and Islands in SQL: Missing Numbers and Streaks

6 min read 0 views

Solve the gaps and islands problem in SQL: find missing invoice numbers with LEAD and consecutive login streaks with the ROW_NUMBER difference trick.

“Which invoice numbers are missing?” and “What is each student’s longest login streak?” are two sides of a classic SQL puzzle called gaps and islands. A gap is a hole in a sequence; an island is an unbroken run of values. Both are solved with window functions, and the island trick in particular is a favourite in data analyst interviews.

In this lesson you will learn

  • Finding missing numbers with LEAD
  • The “value minus row number” trick for islands
  • Turning islands into start, end and length
  • Finding the longest streak for each person

You should know window functions, especially ROW_NUMBER and LEAD, and CTEs.

Finding Gaps

-- Invoice numbers should run 1001, 1002, ... Which are missing?
CREATE TABLE invoices (no INTEGER PRIMARY KEY);
INSERT INTO invoices VALUES (1001),(1002),(1003),(1006),(1007),(1010),(1011),(1012);

SELECT no + 1 AS gap_starts,
       next_no - 1 AS gap_ends,
       next_no - no - 1 AS missing
FROM (SELECT no, LEAD(no) OVER (ORDER BY no) AS next_no FROM invoices)
WHERE next_no - no > 1;

Output

+------------+----------+---------+
| gap_starts | gap_ends | missing |
+------------+----------+---------+
| 1004       | 1005     | 2       |
| 1008       | 1009     | 2       |
+------------+----------+---------+
(2 rows)
  • LEAD(no) OVER (ORDER BY no) puts the next invoice number beside each row. After 1003 comes 1006.
  • When the next number is more than 1 bigger, there is a gap. It starts at no + 1 and ends at next_no − 1.
  • Two gaps appear: 1004–1005 and 1008–1009, two missing invoices each. An accountant would want to know why.

Finding Islands (Streaks)

-- Days a student logged in to the learning site
CREATE TABLE logins (student TEXT, day TEXT);
INSERT INTO logins VALUES
 ('Tania','2026-03-01'),('Tania','2026-03-02'),('Tania','2026-03-03'),
 ('Tania','2026-03-05'),('Tania','2026-03-06'),
 ('Tania','2026-03-09'),('Tania','2026-03-10'),('Tania','2026-03-11'),('Tania','2026-03-12'),
 ('Arif','2026-03-02'),('Arif','2026-03-04'),('Arif','2026-03-05');

-- See the trick: inside a streak, day-of-month minus row number stays the same
SELECT day,
       CAST(strftime('%d', day) AS INTEGER) AS day_no,
       ROW_NUMBER() OVER (ORDER BY day) AS rn,
       CAST(strftime('%d', day) AS INTEGER) - ROW_NUMBER() OVER (ORDER BY day) AS grp
FROM logins
WHERE student = 'Tania';

-- Islands: day number minus row number is constant inside a streak
WITH numbered AS (
  SELECT student, day,
         julianday(day) - ROW_NUMBER() OVER (PARTITION BY student ORDER BY day) AS grp
  FROM logins
)
SELECT student,
       MIN(day) AS streak_start,
       MAX(day) AS streak_end,
       COUNT(*) AS days
FROM numbered
GROUP BY student, grp
ORDER BY student, streak_start;

-- Longest streak per student
WITH numbered AS (
  SELECT student, day,
         julianday(day) - ROW_NUMBER() OVER (PARTITION BY student ORDER BY day) AS grp
  FROM logins
), streaks AS (
  SELECT student, COUNT(*) AS days FROM numbered GROUP BY student, grp
)
SELECT student, MAX(days) AS longest_streak FROM streaks GROUP BY student;

Output

+------------+--------+----+-----+
| day        | day_no | rn | grp |
+------------+--------+----+-----+
| 2026-03-01 | 1      | 1  | 0   |
| 2026-03-02 | 2      | 2  | 0   |
| 2026-03-03 | 3      | 3  | 0   |
| 2026-03-05 | 5      | 4  | 1   |
| 2026-03-06 | 6      | 5  | 1   |
| 2026-03-09 | 9      | 6  | 3   |
| 2026-03-10 | 10     | 7  | 3   |
| 2026-03-11 | 11     | 8  | 3   |
| 2026-03-12 | 12     | 9  | 3   |
+------------+--------+----+-----+
(9 rows)

+---------+--------------+------------+------+
| student | streak_start | streak_end | days |
+---------+--------------+------------+------+
| Arif    | 2026-03-02   | 2026-03-02 | 1    |
| Arif    | 2026-03-04   | 2026-03-05 | 2    |
| Tania   | 2026-03-01   | 2026-03-03 | 3    |
| Tania   | 2026-03-05   | 2026-03-06 | 2    |
| Tania   | 2026-03-09   | 2026-03-12 | 4    |
+---------+--------------+------------+------+
(5 rows)

+---------+----------------+
| student | longest_streak |
+---------+----------------+
| Arif    | 2              |
| Tania   | 4              |
+---------+----------------+
(2 rows)

The first result shows why the trick works. Inside a streak, both the day number and the row number go up by 1 each step, so their difference (grp) stays the same. When a day is skipped, the day number jumps but the row number does not, so the difference changes. Each distinct grp value marks one island.

  • The real query uses julianday(day), which counts days continuously across months and years, instead of the day of the month.
  • PARTITION BY student restarts the row numbers for each student, so their streaks are computed separately.
  • Grouping by student, grp collapses each island to one row with its first day, last day and length. Tania has three streaks: 3, 2 and 4 days.
  • The last query keeps only the longest streak per student: 4 days for Tania and 2 for Arif.

The same pattern works for any sequence: consecutive seat numbers, months with a sale, or days a sensor stayed above a limit. For numbers instead of dates, subtract the row number from the number itself.

Common Mistakes

  1. Duplicate values in the sequence. Two logins on the same day break the trick, because the row number moves while the day does not. Use SELECT DISTINCT student, day first, or DENSE_RANK instead of ROW_NUMBER.
  2. Using day-of-month across months. March 31 to April 1 would look like a jump of −30. Use julianday or a date difference.
  3. Forgetting PARTITION BY when there are several people or devices.
  4. Ordering by text that is not in ISO format. “5/3/2026” does not sort like a date; store dates as YYYY-MM-DD.

Practice Exercises

Exercise 1. Using logins, list the days in March 1–12 on which Tania did not log in. (Hint: walk her logins with LEAD.)

Show answer
SELECT date(day, '+1 day') AS gap_starts,
       date(next_day, '-1 day') AS gap_ends
FROM (SELECT day, LEAD(day) OVER (ORDER BY day) AS next_day
      FROM logins WHERE student = 'Tania')
WHERE julianday(next_day) - julianday(day) > 1;

The gaps are March 4 (start and end on the same day) and March 7–8.

Exercise 2. Find the islands in the invoice numbers instead of the gaps.

Show answer
SELECT MIN(no) AS first_no, MAX(no) AS last_no, COUNT(*) AS invoices
FROM (SELECT no, no - ROW_NUMBER() OVER (ORDER BY no) AS grp FROM invoices)
GROUP BY grp;

The islands are 1001–1003, 1006–1007 and 1010–1012.

Frequently Asked Questions

Can I find gaps without window functions?

Yes. A self join or NOT EXISTS works: find each number n where n + 1 does not exist in the table. Window functions are usually clearer and faster on large tables.

How do I find streaks that allow one day off?

Use LAG to compare each day with the previous one, mark a new streak whenever the difference is more than 2 days, and take a running SUM of those marks as the group number.

Summary

  • Gaps: compare each value with the next using LEAD.
  • Islands: value minus ROW_NUMBER is constant inside a run.
  • Group by that difference to get start, end and length.
  • Remove duplicates and use real date arithmetic first.

Next: Median, Percentiles and NTILE in SQL.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *