PREP WITH PROOF
Menu
SQL & DATA ENGINEERING / PRACTICAL GUIDE

SQL Gaps and Islands: Find Consecutive Date Streaks in SQLite

Find daily streaks and missing date intervals with SQLite LAG and a running SUM. Handle duplicate events, per-user partitions and report boundaries with a tested Python lab.

THE QUICK ANSWER

Deduplicate activity to one row per user and calendar date, use LAG to mark nonconsecutive dates, and cumulatively sum boundary markers to label islands. Group each island for its inclusive start, end and active-day count. Internal gaps need two observed endpoints; a full missing-day report also needs a reporting calendar and user population.

Find runs of active days without counting repeated events

A login table records events, while a streak report counts days. That difference is the source of many incorrect gaps-and-islands queries. Three logins on Monday and one on Tuesday represent a two-day streak, even though the raw table contains four rows. Sorting the events and counting them cannot answer the question until the input has the right grain.

This guide builds a SQLite query for consecutive calendar-day activity, separately for each user. An island is a maximal run of observed days with no missing day between neighbors. An internal gap is a missing interval between two observed days for that same user. Both outputs come from one explicitly defined daily input.

The runnable lab includes duplicate events, shuffled input, two users and a leap-day boundary. It compares SQL output with a separate Python date-walking implementation across 300 seeded fixtures. These are synthetic correctness checks, not a performance benchmark or evidence about a production activity dataset.

Define the daily contract before writing the window functions

The example accepts non-null user IDs and valid, canonical YYYY-MM-DD date strings. Each date is already assigned to the reporting calendar. The SQL is not a timestamp parser, time-zone converter or date-quality validator. The Python reference validates the fixture dates before inserting them; the illustrative SQL table only enforces non-null values.

In an application, decide which calendar owns the day before deduplication: UTC, an organization-wide zone or a user-specific zone. Events around midnight can move between days under different policies. Store or derive that day consistently upstream. A local calendar-day streak also does not mean every pair of events is exactly 24 hours apart.

The deduplication key is (user_id, activity_day). Two users active on the same date remain separate observations. An absent user produces no output. Null dates, malformed strings and mixed timestamp/date formats should be rejected or quarantined before this query; silently filtering them out can turn a data-quality problem into an apparently real gap.

Our reporting unit is one calendar day. Weekends count as days. If Friday followed by Monday should be consecutive, this is a business-calendar problem: map eligible dates to an ordered business-day sequence and define adjacency in that sequence instead.

Deduplicate, inspect the previous day, then number each island

The days CTE establishes one row per user per date. The next CTE uses LAG within each user partition to expose the preceding observed day. With canonical date strings, the explicit date ordering matches chronological ordering. The first day starts an island; any subsequent day starts another when its distance from its predecessor differs from one day.

The labeled CTE cumulatively adds those start markers. All rows in a run receive the same island ID. Grouping by user and island ID then gives the start date, end date and number of active days. An island ID is a temporary grouping label for this result, not a durable business identifier: adding earlier history can renumber later islands.

The running SUM declares a ROWS frame from the partition start through the current row. After deduplication, dates are unique within a user, making the step order unambiguous. Keeping the frame explicit communicates that the label advances one daily row at a time. The existing window-frames guide explains peer groups and other frame-sensitive calculations.

SQLite restricts where window functions may appear, so the query separates the previous-day calculation, boundary marker and cumulative label into ordinary CTEs. This also makes each intermediate relation easy to inspect. The final ORDER BY is explicit; an ordering inside OVER describes the window calculation and does not promise the presentation order of the complete result.

Check the leap-day example by hand

Ada has events on February 28, February 29 twice, March 1, March 4 and March 5 of 2024. The duplicate February 29 disappears in days. The first three distinct dates are consecutive across the month boundary; the missing March 2 and March 3 separate them from the next two-day run.

Bo has March 1 and March 3. Partitioning prevents Ada’s March 4 from affecting Bo’s previous-day calculation. Bo therefore has two single-day islands and one missing day. A single observed date is a valid island of length one, not an error or a zero-day interval.

The number of days in an island is inclusive. For a consecutive run, COUNT(*) after daily deduplication agrees with the endpoint distance plus one. Counting the original event rows would inflate Ada’s first run from three days to four events and would measure a different quantity.

user  start       end         active_days
ada   2024-02-28  2024-03-01  3
ada   2024-03-04  2024-03-05  2
bo    2024-03-01  2024-03-01  1
bo    2024-03-03  2024-03-03  1

Run both SQL outputs against an independent date-walking reference

Save the complete block as streaks.py and run python streaks.py. It uses only the Python standard library and an in-memory SQLite connection. The SQL strings at the top can also be used with an activity table obeying the input contract. ISLANDS returns maximal runs; GAPS returns bounded missing intervals.

The local execution used SQLite 3.53.1 and passed 1,218 checks. Each fixture checks exact island rows, exact gap rows, conservation of distinct daily observations and positive gap sizes. Two additional assertions pin the worked example to explicit expected rows. The seeded fixtures contain three users, repeated dates, arbitrary insertion order and dates spanning year and leap-day boundaries.

The reference walks sorted Python date sets instead of using SQL windows or Julian-day subtraction. Agreement is useful evidence about these fixtures. It does not test invalid-date handling, arbitrary Unicode user sorting, other database engines, concurrent writes, indexes or query latency.

import sqlite3
from datetime import date, timedelta
from collections import defaultdict
from random import Random

PREFIX = """
WITH days AS (
  SELECT DISTINCT user_id, activity_day FROM activity
), previous AS (
  SELECT user_id, activity_day,
         lag(activity_day) OVER (
           PARTITION BY user_id ORDER BY activity_day
         ) AS previous_day
  FROM days
), marked AS (
  SELECT *, CASE
    WHEN previous_day IS NULL
      OR julianday(activity_day) - julianday(previous_day) <> 1
    THEN 1 ELSE 0 END AS starts_island
  FROM previous
), labeled AS (
  SELECT *, sum(starts_island) OVER (
    PARTITION BY user_id ORDER BY activity_day
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  ) AS island_id
  FROM marked
)
"""
ISLANDS = PREFIX + """
SELECT user_id, min(activity_day), max(activity_day), count(*)
FROM labeled
GROUP BY user_id, island_id
ORDER BY user_id, min(activity_day)
"""
GAPS = PREFIX + """
SELECT user_id, date(previous_day, '+1 day'),
       date(activity_day, '-1 day'),
       CAST(julianday(activity_day) - julianday(previous_day) AS INTEGER) - 1
FROM previous
WHERE julianday(activity_day) - julianday(previous_day) > 1
ORDER BY user_id, activity_day
"""

def reference(rows):
    by_user = defaultdict(set)
    for user, day in rows:
        parsed = date.fromisoformat(day)
        if parsed.isoformat() != day:
            raise ValueError('Use canonical YYYY-MM-DD dates')
        by_user[user].add(parsed)
    islands, gaps = [], []
    for user in sorted(by_user):
        ordered = sorted(by_user[user])
        start = previous = ordered[0]
        count = 1
        for day in ordered[1:]:
            if day == previous + timedelta(days=1):
                count += 1
            else:
                islands.append((user, start.isoformat(), previous.isoformat(), count))
                gaps.append((user, (previous + timedelta(days=1)).isoformat(),
                             (day - timedelta(days=1)).isoformat(),
                             (day - previous).days - 1))
                start, count = day, 1
            previous = day
        islands.append((user, start.isoformat(), previous.isoformat(), count))
    return islands, gaps

connection = sqlite3.connect(':memory:')
connection.execute('CREATE TABLE activity(user_id TEXT NOT NULL, activity_day TEXT NOT NULL)')
checks = 0

def verify(rows):
    global checks
    expected_islands, expected_gaps = reference(rows)
    connection.execute('DELETE FROM activity')
    connection.executemany('INSERT INTO activity VALUES (?, ?)', rows)
    actual_islands = connection.execute(ISLANDS).fetchall()
    actual_gaps = connection.execute(GAPS).fetchall()
    assert actual_islands == expected_islands
    assert actual_gaps == expected_gaps
    assert sum(row[3] for row in actual_islands) == len(set(rows))
    assert all(row[3] > 0 for row in actual_gaps)
    checks += 4
    return actual_islands, actual_gaps

sample = [('ada', d) for d in ['2024-02-28', '2024-02-29', '2024-02-29',
                              '2024-03-01', '2024-03-04', '2024-03-05']]
sample += [('bo', '2024-03-01'), ('bo', '2024-03-03')]
islands, gaps = verify(list(reversed(sample)))
assert islands == [('ada', '2024-02-28', '2024-03-01', 3),
                   ('ada', '2024-03-04', '2024-03-05', 2),
                   ('bo', '2024-03-01', '2024-03-01', 1),
                   ('bo', '2024-03-03', '2024-03-03', 1)]
assert gaps == [('ada', '2024-03-02', '2024-03-03', 2),
                ('bo', '2024-03-02', '2024-03-02', 1)]
checks += 2
verify([])
verify([('solo', '2024-12-31')] * 4)
verify([('year', d) for d in ['2023-12-31', '2024-01-01', '2024-01-03']])
rng = Random(20261104)
base = date(2023, 12, 1)
for _ in range(300):
    rows = []
    for user in ['ada', 'bo', 'cy']:
        for offset in range(130):
            if rng.random() < 0.45:
                day = (base + timedelta(days=offset)).isoformat()
                rows.extend([(user, day)] * rng.randint(1, 3))
    rng.shuffle(rows)
    verify(rows)
print('SQLite', sqlite3.sqlite_version, '|', checks, 'checks passed')
print('Islands:', islands)
print('Internal gaps:', gaps)
connection.close()

Internal gaps have two known endpoints

The gap query reads the previous relation directly. If two observed dates differ by more than one day, the missing interval begins one day after the earlier observation and ends one day before the later observation. Its size is the distance between observations minus one. Adjacent dates create no gap row.

This deliberately excludes absence before the first observation and after the last observation. Without a reporting interval, those edges have no finite bounds. To report all missing dates in a month, define the start and end dates and the population of users first, then compare an eligible-date calendar with observed daily activity. Users with zero observations require that separate population relation.

Do not interpret a missing observation as proof that someone did no work. Collection outages, delayed ingestion and filtering can all remove evidence. Pair the metric with the completeness assumptions of the source system before using it in an operational report.

A date filter can split a real streak at the report boundary

Consider a user active every day from January 28 through February 3. Filtering the source to February before windowing produces a three-day island beginning February 1. That is correct for activity observed inside February, but it is not the full seven-day streak that overlaps the month.

Choose the report meaning first. To find full historical islands that overlap an interval, compute the necessary historical islands before selecting those whose end is on or after the interval start and whose start is on or before the interval end. To measure only days inside the interval, filter the daily input and describe the result as clipped.

A one-day lookback can reveal whether an interval starts in the middle of a streak, but cannot recover an arbitrarily long streak’s true starting date. Either read enough history to find the boundary or maintain a correctly updated summary. Late-arriving activity can join two islands, so summaries need a recomputation policy as well as an append path.

Choose adjacency rules instead of swapping functions blindly

A familiar alternative groups a consecutive sequence by a day ordinal minus ROW_NUMBER. Within a daily run, both increase by one, so their difference stays constant. That reasoning depends on unique daily rows, the correct user partition and a stable day ordinal. Applying row numbers directly to duplicate events breaks the invariant.

The boundary-marker method is easier to adapt when continuity has a different rule. For example, sessionization could mark a boundary when a timestamp difference exceeds a chosen inactivity threshold. That changes the metric: allowing a missing day within a session does not make its observed dates consecutive.

Likewise, minimum streak length and longest streak are reporting choices after islands exist. Filter grouped islands by their active-day count. If several islands tie for longest, decide whether to return all ties or select one using an explicit secondary rule such as latest ending date. Do not let incidental query order choose a winner.

Inspect the intermediate days before tuning the final query

When results look wrong, inspect days for one user, then previous, then labeled. Repeated dates in days indicate the wrong grain or inconsistent formatting. Unexpected boundaries point to missing observations or a calendar policy mismatch. A running label that crosses users usually means PARTITION BY or the final grouping key is incomplete.

A candidate index on the stored daily key can be evaluated against your workload, but DISTINCT and window processing still need measurement with realistic data and query plans. This lab makes no index-speed claim. If daily uniqueness is a persistent invariant, consider a dedicated daily table with an appropriate unique key rather than treating the raw event table as already deduplicated.

The reliable path is to settle the calendar and grain, build daily observations, mark boundaries and aggregate runs. Keep bounded internal gaps separate from absence over a reporting calendar. Once those choices are explicit, streak lengths become an auditable property of the supplied observations rather than a surprising side effect of duplicate rows or date filters.

KEEP THESE THREE THINGS

Your next steps

  1. Define the reporting day and deduplicate before applying window functions.
  2. Partition every sequence calculation by its entity and order dates explicitly.
  3. Distinguish internal gaps from absence at the reporting interval edges.
  4. Choose full-history or clipped streak semantics before filtering dates.

Sources & official resources

Linked resources checked on 2026-11-04. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →