Finding Consecutive Ranges: Gaps and Islands

A run of consecutive numbers or dates is an island, and a missing part between them is a gap. "Consecutive login days", "broken serial numbers", and "periods where the same status continues" are all this problem. You cannot tell from one row alone; you must compare with the previous and next rows, so it is solved with LAG, LEAD, and ROW_NUMBER from Window functions.

The examples use a small table built with (VALUES …) t(column). In the numbers 1, 2, 3, 5, 6, 8, 9, 10, 11, 15, the gaps are 4, 7, and 12-14, and the islands are 1-3, 5-6, 8-11, and 15.

Finding gaps: LAG, LEAD

After sorting, if the difference from the immediately preceding value is greater than 1, there is a gap between them.

Difference from the previous value

SELECT x,
       LAG(x) OVER (ORDER BY x)     AS prev_x,
       x - LAG(x) OVER (ORDER BY x) AS step
FROM (VALUES (1), (2), (3), (5), (6), (8), (9), (10), (11), (15)) t(x)
ORDER BY x

There is a gap before each row with step of 2 or more. To get the start and end of each gap directly, fetch the next value with LEAD and output from current + 1 to next - 1. Window functions cannot be used in WHERE, so wrap the query in an inline view.

Start and end of each gap

SELECT x + 1 AS gap_start, next_x - 1 AS gap_end
FROM (
  SELECT x, LEAD(x) OVER (ORDER BY x) AS next_x
  FROM (VALUES (1), (2), (3), (5), (6), (8), (9), (10), (11), (15)) t(x)
) s
WHERE next_x - x > 1
ORDER BY gap_start

The result is three rows: (4, 4), (7, 7), (12, 14).

Grouping islands: value - ROW_NUMBER

Consecutive values increase by 1, and ROW_NUMBER() also increases by 1, so their difference is constant within an island. After a gap, only the value jumps further, so the difference changes. Using this difference as the grouping key in GROUP BY yields one row per island.

xROW_NUMBERx - ROW_NUMBER
1, 2, 31, 2, 30
5, 64, 51
8, 9, 10, 116, 7, 8, 92
15105

Start, end, and length of each island

SELECT MIN(x) AS start_x, MAX(x) AS end_x, COUNT(*) AS len
FROM (
  SELECT x, x - ROW_NUMBER() OVER (ORDER BY x) AS grp
  FROM (VALUES (1), (2), (3), (5), (6), (8), (9), (10), (11), (15)) t(x)
) s
GROUP BY grp
ORDER BY start_x

Consecutive login days

Dates work the same way. Subtracting as many days as the row number from each date gives the same date for consecutive dates. The expression for subtracting days from a date differs by DB.

DBdate - n daysCaution
Oracled - n
PostgreSQLd - n (date - integer)ROW_NUMBER() is bigint, so you get an error that no date - bigint operator exists. CAST(… AS integer) is required
SQL ServerDATEADD(day, -n, d)

User 1 logged in on March 1-3, 5-6, and 9, and user 2 on March 2-5 and 8; user 1's March 2 is recorded twice. If the same day has two rows, only the row number increases and the ranges split incorrectly, so first reduce to one row per day with DISTINCT.

Oracle · Consecutive login ranges

WITH logins AS (
  SELECT * FROM (VALUES (1, DATE '2025-03-01'), (1, DATE '2025-03-02'), (1, DATE '2025-03-02'),
                        (1, DATE '2025-03-03'), (1, DATE '2025-03-05'), (1, DATE '2025-03-06'),
                        (1, DATE '2025-03-09'), (2, DATE '2025-03-02'), (2, DATE '2025-03-03'),
                        (2, DATE '2025-03-04'), (2, DATE '2025-03-05'), (2, DATE '2025-03-08')) t(user_id, login_dt)
), days AS (
  SELECT DISTINCT user_id, login_dt FROM logins
), g AS (
  SELECT user_id, login_dt,
         login_dt - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_dt) AS grp
  FROM days
)
SELECT user_id, MIN(login_dt) AS start_dt, MAX(login_dt) AS end_dt, COUNT(*) AS days
FROM g
GROUP BY user_id, grp
ORDER BY user_id, start_dt

PostgreSQL · Consecutive login ranges

WITH logins AS (
  SELECT * FROM (VALUES (1, DATE '2025-03-01'), (1, DATE '2025-03-02'), (1, DATE '2025-03-02'),
                        (1, DATE '2025-03-03'), (1, DATE '2025-03-05'), (1, DATE '2025-03-06'),
                        (1, DATE '2025-03-09'), (2, DATE '2025-03-02'), (2, DATE '2025-03-03'),
                        (2, DATE '2025-03-04'), (2, DATE '2025-03-05'), (2, DATE '2025-03-08')) t(user_id, login_dt)
), days AS (
  SELECT DISTINCT user_id, login_dt FROM logins
), g AS (
  SELECT user_id, login_dt,
         login_dt - CAST(ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_dt) AS integer) AS grp
  FROM days
)
SELECT user_id, MIN(login_dt) AS start_dt, MAX(login_dt) AS end_dt, COUNT(*) AS days
FROM g
GROUP BY user_id, grp
ORDER BY user_id, start_dt

SQL Server · Consecutive login ranges

WITH logins AS (
  SELECT user_id, CAST(d AS date) AS login_dt
  FROM (VALUES (1, '2025-03-01'), (1, '2025-03-02'), (1, '2025-03-02'), (1, '2025-03-03'),
               (1, '2025-03-05'), (1, '2025-03-06'), (1, '2025-03-09'), (2, '2025-03-02'),
               (2, '2025-03-03'), (2, '2025-03-04'), (2, '2025-03-05'), (2, '2025-03-08')) t(user_id, d)
), days AS (
  SELECT DISTINCT user_id, login_dt FROM logins
), g AS (
  SELECT user_id, login_dt,
         DATEADD(day, -ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_dt), login_dt) AS grp
  FROM days
)
SELECT user_id, MIN(login_dt) AS start_dt, MAX(login_dt) AS end_dt, COUNT(*) AS days
FROM g
GROUP BY user_id, grp
ORDER BY user_id, start_dt

On all three DBs, user 1 gets ranges of 3, 2, and 1 days, and user 2 gets ranges of 4 and 1 days. "Longest consecutive login streak" is MAX(days) over this result.

Splitting into ranges whenever the status changes

A column where the same value reappears, such as ON, ON, OFF, OFF, OFF, ON, OFF, OFF, cannot be grouped by value - row number. Instead, split it in two steps.

  1. Compare with the previous status using LAG, and attach 1 to rows that changed (or the first row) and 0 otherwise.
  2. The running total of that flag is the range number, because it increases by 1 at each change.

Change flag and running total

WITH flagged AS (
  SELECT seq, status,
         CASE WHEN status = LAG(status) OVER (ORDER BY seq) THEN 0 ELSE 1 END AS chg
  FROM (VALUES (1, 'ON'), (2, 'ON'), (3, 'OFF'), (4, 'OFF'), (5, 'OFF'), (6, 'ON'), (7, 'OFF'), (8, 'OFF')) t(seq, status)
), grouped AS (
  SELECT seq, status, chg,
         SUM(chg) OVER (ORDER BY seq ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS grp
  FROM flagged
)
SELECT grp, status, MIN(seq) AS start_seq, MAX(seq) AS end_seq, COUNT(*) AS len
FROM grouped
GROUP BY grp, status
ORDER BY grp

The result is four ranges: ON 1-2, OFF 3-5, ON 6, OFF 7-8. On the first row, LAG is NULL, so the comparison is not true and the row gets 1. The flag and the running total cannot be nested in one SELECT (a window function inside a window function), so the CTE is split into two steps.

The same result also comes from the difference of two row numbers. Subtracting the per-status row number from the overall row number gives a constant difference while the same status continues. This difference can coincide for different statuses (below, ON 6 and OFF 7-8 are both 3), so include status in the grouping key as well.

Difference of two row numbers

SELECT status, grp, MIN(seq) AS start_seq, MAX(seq) AS end_seq, COUNT(*) AS len
FROM (
  SELECT seq, status,
         ROW_NUMBER() OVER (ORDER BY seq)
           - ROW_NUMBER() OVER (PARTITION BY status ORDER BY seq) AS grp
  FROM (VALUES (1, 'ON'), (2, 'ON'), (3, 'OFF'), (4, 'OFF'), (5, 'OFF'), (6, 'ON'), (7, 'OFF'), (8, 'OFF')) t(seq, status)
) s
GROUP BY status, grp
ORDER BY start_seq

Order data: a new range after a break of more than 30 days

Changing the change-flag condition to "more than 30 days have passed since the previous order" splits orders into activity ranges.

Oracle, PostgreSQL · Split orders into ranges by 30-day gaps

WITH flagged AS (
  SELECT ord_id, ord_dt,
         CASE WHEN ord_dt <= LAG(ord_dt) OVER (ORDER BY ord_dt, ord_id) + INTERVAL '30' DAY
              THEN 0 ELSE 1 END AS new_seg
  FROM orders
  WHERE cust_id = 101
), seg AS (
  SELECT ord_id, ord_dt,
         SUM(new_seg) OVER (ORDER BY ord_dt, ord_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS seg_no
  FROM flagged
)
SELECT seg_no, MIN(ord_dt) AS first_dt, MAX(ord_dt) AS last_dt, COUNT(*) AS orders
FROM seg
GROUP BY seg_no
ORDER BY seg_no

SQL Server · Split orders into ranges by 30-day gaps

WITH flagged AS (
  SELECT ord_id, ord_dt,
         CASE WHEN ord_dt <= DATEADD(day, 30, LAG(ord_dt) OVER (ORDER BY ord_dt, ord_id))
              THEN 0 ELSE 1 END AS new_seg
  FROM orders
  WHERE cust_id = 101
), seg AS (
  SELECT ord_id, ord_dt,
         SUM(new_seg) OVER (ORDER BY ord_dt, ord_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS seg_no
  FROM flagged
)
SELECT seg_no, MIN(ord_dt) AS first_dt, MAX(ord_dt) AS last_dt, COUNT(*) AS orders
FROM seg
GROUP BY seg_no
ORDER BY seg_no

TIP If the sort key has equal values, the row LAG points to can differ between executions. Append a unique column, as in ORDER BY ord_dt, ord_id, to fix the order.