Gaps and Islands: Finding Consecutive Ranges and Missing Values
How to solve gaps-and-islands problems in SQL with window functions: finding missing dates and IDs, grouping consecutive days into ranges, user streaks, runs of the same status, splitting events into sessions, and merging overlapping date ranges.
kvi5hnuCode Sprout team member11 min readOn this page
"Which days had no sales?" "What's each user's longest daily streak?" "When was the machine down, and for how long?" "Split these page views into visits." "Which periods is this pitch booked for?"
These questions look different, but they share one structure. The data is a sequence of rows, and the answer depends on where the sequence is unbroken and where it breaks. The unbroken runs are called islands, and the breaks between them are gaps. The name "gaps and islands" comes from SQL folklore, and these problems appear constantly in reporting, analytics and interviews.
Before window functions, they needed tangled self-joins. With ROW_NUMBER, LAG and running sums (articles 27–29), each has a short, standard solution. This article covers six patterns:
| Problem | Technique |
|---|---|
| Missing values | a generated series with NOT EXISTS, or LEAD |
| Consecutive values (dates, IDs) | value minus ROW_NUMBER |
| Streaks per entity | the same, with PARTITION BY |
| Runs of the same value | the difference of two ROW_NUMBERs |
| Sessions separated by long gaps | LAG to flag starts, a running SUM to number them |
| Overlapping ranges | a running MAX of the end, then flag and number |
The examples begin with the daily_sales table from article 28: takings from 1 to 8 March, with no row for 4 March.
Finding gaps
There are two ways to find missing values. The first lists every value that should exist and checks which are absent. The second compares each row with the next and reports the space between them:
-- Daily takings of a market stall; no trading on 4 March
CREATE TABLE daily_sales (
day DATE PRIMARY KEY,
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO daily_sales VALUES
(DATE '2026-03-01', 120.00),
(DATE '2026-03-02', 80.00),
(DATE '2026-03-03', 150.00),
(DATE '2026-03-05', 60.00),
(DATE '2026-03-06', 200.00),
(DATE '2026-03-07', 90.00),
(DATE '2026-03-08', 110.00);
-- Gaps: which dates have no row?
SELECT d::date AS missing_day
FROM generate_series(DATE '2026-03-01', DATE '2026-03-08', INTERVAL '1 day') AS d
WHERE NOT EXISTS (SELECT 1 FROM daily_sales s WHERE s.day = d::date)
ORDER BY missing_day;
-- Gaps as ranges, without a date series: compare each row with the next one
SELECT day + 1 AS gap_starts,
next_day - 1 AS gap_ends,
next_day - day - 1 AS missing_days
FROM (SELECT day, LEAD(day) OVER (ORDER BY day) AS next_day
FROM daily_sales) AS t
WHERE next_day - day > 1;
missing_day
-------------
2026-03-04
(1 row)
gap_starts | gap_ends | missing_days
------------+------------+--------------
2026-03-04 | 2026-03-04 | 1
(1 row)
- The first query generates every date from 1 to 8 March with
generate_series(article 41 covers date series in detail) and keeps the dates with no sales row. It needs the expected start and end, but it also finds gaps at the edges, such as a missing 1 March. - The second query uses
LEAD(day)to find each row's next date. When the next date is more than one day later, the days in between are missing. It returns one row per gap, however long, which is better when gaps are long (a 90-day gap is one row, not 90). It can't see gaps before the first row or after the last.
The same two techniques find missing IDs in a sequence: generate_series(1, MAX(id)) with NOT EXISTS, or LEAD(id) - id > 1. Gaps in an identity column are normal, though. Rolled-back inserts and deleted rows leave them, and you shouldn't try to prevent them (article 54).
Finding islands: value minus row number
To group consecutive dates into ranges, the standard trick is to subtract a row number from each value:
-- Daily takings of a market stall; no trading on 4 March
CREATE TABLE daily_sales (
day DATE PRIMARY KEY,
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO daily_sales VALUES
(DATE '2026-03-01', 120.00),
(DATE '2026-03-02', 80.00),
(DATE '2026-03-03', 150.00),
(DATE '2026-03-05', 60.00),
(DATE '2026-03-06', 200.00),
(DATE '2026-03-07', 90.00),
(DATE '2026-03-08', 110.00);
-- Islands: consecutive days get the same (day - row number)
SELECT day,
ROW_NUMBER() OVER (ORDER BY day) AS rn,
day - ROW_NUMBER() OVER (ORDER BY day)::integer AS island
FROM daily_sales
ORDER BY day;
-- One row per island
SELECT MIN(day) AS island_start,
MAX(day) AS island_end,
COUNT(*) AS days,
SUM(amount) AS takings
FROM (SELECT day, amount,
day - ROW_NUMBER() OVER (ORDER BY day)::integer AS island
FROM daily_sales) AS t
GROUP BY island
ORDER BY island_start;
day | rn | island
------------+----+------------
2026-03-01 | 1 | 2026-02-28
2026-03-02 | 2 | 2026-02-28
2026-03-03 | 3 | 2026-02-28
2026-03-05 | 4 | 2026-03-01
2026-03-06 | 5 | 2026-03-01
2026-03-07 | 6 | 2026-03-01
2026-03-08 | 7 | 2026-03-01
(7 rows)
island_start | island_end | days | takings
--------------+------------+------+---------
2026-03-01 | 2026-03-03 | 3 | 350.00
2026-03-05 | 2026-03-08 | 4 | 460.00
(2 rows)
Why it works: within a run of consecutive dates, each date is one day after the previous one, and the row number is also one more than the previous one. They rise in step, so day - rn stays the same throughout the run. After a gap, the date jumps by more than one while the row number still rises by one, so the difference changes. The value of the difference means nothing on its own (28 February and 1 March here). It's just a label shared by the members of each island.

The second query groups by that label and uses MIN, MAX, COUNT and SUM to describe each island: the stall traded for 3 days, then after a 1-day break for another 4 days.
Details that matter:
- In PostgreSQL,
date - integergives a date, butROW_NUMBER()returnsbigint, so the query casts it tointeger. In other databases, use the date arithmetic function:DATEADD(day, -rn, day)in SQL Server,DATE_SUB(day, INTERVAL rn DAY)in MySQL,day - rnin Oracle. - The values must be unique. If a date can appear twice, the row number rises while the date doesn't, which breaks the trick. Use
DENSE_RANK()instead ofROW_NUMBER(), or selectDISTINCTdates first. - For integer IDs, the same trick is simply
id - ROW_NUMBER() OVER (ORDER BY id).
Streaks per user
Adding PARTITION BY applies the same trick to each user separately. The next table records the days on which each user of a learning app practised:
-- Days on which each user practised
CREATE TABLE practice_days (
user_name TEXT NOT NULL,
day DATE NOT NULL,
PRIMARY KEY (user_name, day)
);
INSERT INTO practice_days VALUES
('asha', DATE '2026-05-01'), ('asha', DATE '2026-05-02'), ('asha', DATE '2026-05-03'),
('asha', DATE '2026-05-05'), ('asha', DATE '2026-05-06'),
('ben', DATE '2026-05-02'), ('ben', DATE '2026-05-04'), ('ben', DATE '2026-05-05'),
('ben', DATE '2026-05-06'), ('ben', DATE '2026-05-07'),
('chen', DATE '2026-05-03');
-- Every streak per user, and each user's longest streak
WITH streaks AS (
SELECT user_name,
MIN(day) AS first_day,
MAX(day) AS last_day,
COUNT(*) AS length
FROM (SELECT user_name, day,
day - ROW_NUMBER() OVER (PARTITION BY user_name
ORDER BY day)::integer AS island
FROM practice_days) AS t
GROUP BY user_name, island
)
SELECT user_name, first_day, last_day, length,
length = MAX(length) OVER (PARTITION BY user_name) AS is_longest
FROM streaks
ORDER BY user_name, first_day;
user_name | first_day | last_day | length | is_longest
-----------+------------+------------+--------+------------
asha | 2026-05-01 | 2026-05-03 | 3 | t
asha | 2026-05-05 | 2026-05-06 | 2 | f
ben | 2026-05-02 | 2026-05-02 | 1 | f
ben | 2026-05-04 | 2026-05-07 | 4 | t
chen | 2026-05-03 | 2026-05-03 | 1 | t
(5 rows)
The streaks CTE produces one row per island per user, and the outer query marks each user's longest streak with MAX(length) OVER (PARTITION BY user_name). Ben's longest streak is 4 days, from 4 to 7 May. To return only the longest streaks, filter on is_longest in a further step, or rank the streaks with ROW_NUMBER and keep number 1 if one row per user is required.
A "current streak" is the island whose last day is today (or yesterday, if today's practice may still come). Filter streaks on last_day >= CURRENT_DATE - 1.
Runs of the same value
Sometimes the island isn't defined by consecutive values, but by consecutive rows with the same value: the periods when a machine was up or down, a price that stayed the same, or a player's winning and losing runs. The trick here is the difference of two row numbers:
-- A machine's status, checked every hour
CREATE TABLE status_checks (
hour INTEGER PRIMARY KEY,
status TEXT NOT NULL
);
INSERT INTO status_checks VALUES
(1, 'up'), (2, 'up'), (3, 'down'), (4, 'down'), (5, 'up'),
(6, 'up'), (7, 'up'), (8, 'down'), (9, 'up');
-- Runs of the same value: the difference of two row numbers
SELECT hour, status,
ROW_NUMBER() OVER (ORDER BY hour) AS rn_all,
ROW_NUMBER() OVER (PARTITION BY status ORDER BY hour) AS rn_status,
ROW_NUMBER() OVER (ORDER BY hour)
- ROW_NUMBER() OVER (PARTITION BY status ORDER BY hour) AS grp
FROM status_checks
ORDER BY hour;
-- One row per run
SELECT status, MIN(hour) AS from_hour, MAX(hour) AS to_hour, COUNT(*) AS hours
FROM (SELECT hour, status,
ROW_NUMBER() OVER (ORDER BY hour)
- ROW_NUMBER() OVER (PARTITION BY status ORDER BY hour) AS grp
FROM status_checks) AS t
GROUP BY status, grp
ORDER BY from_hour;
hour | status | rn_all | rn_status | grp
------+--------+--------+-----------+-----
1 | up | 1 | 1 | 0
2 | up | 2 | 2 | 0
3 | down | 3 | 1 | 2
4 | down | 4 | 2 | 2
5 | up | 5 | 3 | 2
6 | up | 6 | 4 | 2
7 | up | 7 | 5 | 2
8 | down | 8 | 3 | 5
9 | up | 9 | 6 | 3
(9 rows)
status | from_hour | to_hour | hours
--------+-----------+---------+-------
up | 1 | 2 | 2
down | 3 | 4 | 2
up | 5 | 7 | 3
down | 8 | 8 | 1
up | 9 | 9 | 1
(5 rows)
rn_allnumbers all rows in time order.rn_statusnumbers the rows of each status separately.- Within a run of the same status, both numbers rise by one per row, so their difference,
grp, stays constant. When another status interrupts the run,rn_allkeeps rising butrn_statusfor this status doesn't, so the next run of the same status gets a different difference.
Notice that grp alone isn't unique: hours 3–4 (down) and 5–7 (up) both have 2. The group is identified by status and grp together, so the second query groups by both. The result lists five runs: up for 2 hours, down for 2, up for 3, down for 1 and up for 1.
An equivalent approach, often easier to read, flags the rows where the value changes with LAG and numbers the runs with a running sum: the same technique as the next section.
Sessions: splitting events at long gaps
Website analytics groups page views into sessions: a session ends when the user is inactive for more than 30 minutes. Here the islands are defined by a gap threshold, not by exact consecutiveness, so the row-number trick doesn't apply. Instead, use two steps:
-- Page views on a website
CREATE TABLE page_views (
user_name TEXT NOT NULL,
viewed_at TIMESTAMP NOT NULL,
page TEXT NOT NULL
);
INSERT INTO page_views VALUES
('asha', TIMESTAMP '2026-05-01 09:00', '/home'),
('asha', TIMESTAMP '2026-05-01 09:05', '/tents'),
('asha', TIMESTAMP '2026-05-01 09:20', '/cart'),
('asha', TIMESTAMP '2026-05-01 11:00', '/home'),
('asha', TIMESTAMP '2026-05-01 11:10', '/packs'),
('ben', TIMESTAMP '2026-05-01 09:02', '/home'),
('ben', TIMESTAMP '2026-05-01 10:00', '/lighting'),
('ben', TIMESTAMP '2026-05-01 10:25', '/cart');
-- Sessions: a new session starts after 30 minutes without a page view
WITH flagged AS (
SELECT user_name, viewed_at, page,
CASE WHEN viewed_at - LAG(viewed_at) OVER (PARTITION BY user_name
ORDER BY viewed_at)
<= INTERVAL '30 minutes'
THEN 0 ELSE 1 END AS new_session
FROM page_views
),
numbered AS (
SELECT *, SUM(new_session) OVER (PARTITION BY user_name
ORDER BY viewed_at) AS session_no
FROM flagged
)
SELECT user_name, session_no,
MIN(viewed_at) AS started,
MAX(viewed_at) AS ended,
COUNT(*) AS views
FROM numbered
GROUP BY user_name, session_no
ORDER BY user_name, session_no;
user_name | session_no | started | ended | views
-----------+------------+---------------------+---------------------+-------
asha | 1 | 2026-05-01 09:00:00 | 2026-05-01 09:20:00 | 3
asha | 2 | 2026-05-01 11:00:00 | 2026-05-01 11:10:00 | 2
ben | 1 | 2026-05-01 09:02:00 | 2026-05-01 09:02:00 | 1
ben | 2 | 2026-05-01 10:00:00 | 2026-05-01 10:25:00 | 2
(4 rows)
- Flag the first row of each session.
LAG(viewed_at)gives the user's previous view. If it was within 30 minutes, the row continues a session (0). Otherwise, including the first view, whereLAGis NULL and the comparison is unknown, it starts a new one (1). - Number the sessions with a running sum of the flags. Each 1 increments the count, and the rows after it, flagged 0, keep the same number.
Then group by user and session number. Asha's 1 hour 40 minute break splits Asha's views into two sessions. Ben's views at 9 and 10 are 58 minutes apart, so they're separate sessions too.
This flag-and-sum pattern is the most flexible of all. Whatever the rule for "a new group starts here" (the status changed, the gap exceeds a threshold, the balance went negative), write it as a CASE that returns 1 or 0, and a running SUM turns the flags into group numbers.
Merging overlapping ranges
The last pattern works on rows that are already ranges, such as bookings with an arrival and departure date, and merges the ones that overlap or touch into continuous periods:
-- Campsite pitch bookings; some overlap or touch
CREATE TABLE bookings (
booking_id INTEGER PRIMARY KEY,
pitch TEXT NOT NULL,
arrive DATE NOT NULL,
depart DATE NOT NULL -- the morning the guests leave
);
INSERT INTO bookings VALUES
(1, 'A', DATE '2026-07-01', DATE '2026-07-04'),
(2, 'A', DATE '2026-07-03', DATE '2026-07-06'),
(3, 'A', DATE '2026-07-06', DATE '2026-07-08'),
(4, 'A', DATE '2026-07-12', DATE '2026-07-14'),
(5, 'B', DATE '2026-07-02', DATE '2026-07-05'),
(6, 'B', DATE '2026-07-03', DATE '2026-07-04'),
(7, 'B', DATE '2026-07-09', DATE '2026-07-10');
-- Merge overlapping or touching bookings into occupied periods
WITH marked AS (
SELECT pitch, arrive, depart,
CASE WHEN arrive <= MAX(depart) OVER (PARTITION BY pitch
ORDER BY arrive, depart
ROWS BETWEEN UNBOUNDED PRECEDING
AND 1 PRECEDING)
THEN 0 ELSE 1 END AS starts_period
FROM bookings
),
numbered AS (
SELECT *, SUM(starts_period) OVER (PARTITION BY pitch
ORDER BY arrive, depart
ROWS UNBOUNDED PRECEDING) AS period
FROM marked
)
SELECT pitch, MIN(arrive) AS occupied_from, MAX(depart) AS occupied_until,
COUNT(*) AS bookings
FROM numbered
GROUP BY pitch, period
ORDER BY pitch, occupied_from;
pitch | occupied_from | occupied_until | bookings
-------+---------------+----------------+----------
A | 2026-07-01 | 2026-07-08 | 3
A | 2026-07-12 | 2026-07-14 | 1
B | 2026-07-02 | 2026-07-05 | 2
B | 2026-07-09 | 2026-07-10 | 1
(4 rows)
It's flag-and-sum again, with one twist. A booking starts a new period if it begins after every earlier booking has ended. Comparing it with only the previous booking isn't enough: a long earlier booking might still be running while a shorter one in between has ended. So the flag compares arrive with the running maximum of depart over all earlier rows: MAX(depart) OVER (... ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING).
- Pitch A: booking 2 starts on 3 July, before booking 1 ends on 4 July, so they overlap. Booking 3 arrives on 6 July, the day booking 2 departs, so it touches and joins the same period: 1 to 8 July. Booking 4 starts a new period.
- Pitch B: booking 6 lies entirely inside booking 5, and they merge into 2 to 5 July.
For the first booking of each pitch, the running maximum covers no rows and is NULL, so the comparison is unknown and the CASE starts a new period, as intended. Use < instead of <= if touching ranges should stay separate.
PostgreSQL also has range types and, since PostgreSQL 14, multiranges, which merge overlapping ranges directly: range_agg(daterange(arrive, depart)) returns the occupied periods as a multirange. Range types are PostgreSQL-specific, while the window version works everywhere.
What's current
- All the techniques in this article use standard window functions and work in PostgreSQL, MySQL 8.0+, SQL Server, Oracle, SQLite 3.25+ and MariaDB 10.2+. Only the date arithmetic and date-series functions differ.
- Oracle 12c added
MATCH_RECOGNIZE, the SQL standard's row pattern matching, which can find islands, streaks and other sequences declaratively. Trino and Snowflake support it as well. PostgreSQL, MySQL and SQL Server don't. - PostgreSQL 14 added multiranges and
range_agg, and SQL Server 2022 addedGENERATE_SERIESfor generating the expected values when looking for gaps.
Common questions
Why does day - ROW_NUMBER() group consecutive days?
Within a run of consecutive days, the date and the row number both increase by 1 per row, so their difference is constant. A gap makes the date jump further than the row number, which changes the difference.
What if a date can appear more than once?
Use DENSE_RANK() instead of ROW_NUMBER(), so duplicate dates get the same number, or remove duplicates first with DISTINCT.
How do I find gaps at the start or end of a range?
LEAD and LAG only see the space between existing rows. Generate the full expected series and use NOT EXISTS or a left join.
Which technique should I use for "consecutive rows with the same value"?
The difference of two row numbers, grouped by the value and the difference, or LAG to flag value changes plus a running SUM.
Why compare with a running MAX when merging ranges, and not with LAG?
An earlier long range may still be open after the previous, shorter range has ended. The running maximum of the end date covers all earlier ranges.
Are gaps in an ID sequence a problem? No. Identity columns and sequences leave gaps after rollbacks and deletes, by design. Don't rely on IDs being consecutive.
Summary
- Gaps are missing values in a sequence, and islands are unbroken runs. Many reporting questions reduce to finding one or the other.
- Find gaps by generating the expected values and checking with
NOT EXISTS, or by comparing each row with the next usingLEAD. - Group consecutive values by
value - ROW_NUMBER(). UsePARTITION BYfor streaks per entity, andDENSE_RANKif values repeat. - Group runs of the same value by the value and the difference of two row numbers.
- For any other rule, flag the first row of each group with
LAGand aCASE, then number the groups with a runningSUMof the flags. That's how sessions and merged ranges work. - When merging ranges, compare each start with the running
MAXof earlier ends.
Practice questions
Using daily_sales, write a query that returns the longest run of consecutive trading days, with its start and end.
Answer
SELECT MIN(day) AS run_start, MAX(day) AS run_end, COUNT(*) AS days
FROM (SELECT day, day - ROW_NUMBER() OVER (ORDER BY day)::integer AS island
FROM daily_sales) AS t
GROUP BY island
ORDER BY days DESC
FETCH FIRST 1 ROW WITH TIES;
It returns 5 to 8 March, 4 days. WITH TIES returns every run of the same maximum length.
A table tickets(id) holds the IDs 1, 2, 3, 7, 8 and 12. What does id - ROW_NUMBER() OVER (ORDER BY id) return for each row, and which islands does it give?
Answer
The row numbers are 1 to 6, so the differences are 0, 0, 0, 3, 3 and 6. The islands are 1–3, 7–8 and 12.
In the status example, why must the final query group by status, grp and not just grp?
Answer
Different statuses can produce the same difference. Hours 3–4 (down) and 5–7 (up) both have grp = 2. Grouping by grp alone would merge them into one wrong run. Within one status, each run has a distinct difference.
Change the session query so that a new session starts after more than 45 minutes of inactivity. How many sessions does Ben have then?
Answer
Replace INTERVAL '30 minutes' with INTERVAL '45 minutes'. Ben's views at 9 and 10 are still 58 minutes apart, so Ben still has 2 sessions. Asha also still has 2, because Asha's break was 1 hour 40 minutes.
When merging bookings, the condition is arrive <= MAX(depart) OVER (...). What changes if it's arrive < MAX(depart) OVER (...)?
Answer
Touching bookings, where one guest arrives on the day the previous one departs, would no longer merge. On pitch A, booking 3 (arriving 6 July, when booking 2 departs) would start a new period, so pitch A would have three periods: 1–6 July, 6–8 July and 12–14 July.
Previous: LAG, LEAD, FIRST_VALUE and LAST_VALUE: Comparing Rows With Their Neighbours
Next: Inserting Rows With INSERT: Values, Defaults and INSERT ... SELECT

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.