With repeated days, ROW_NUMBER over raw rows reported a longest run of 13 days against a true 5 in SQLite. Gaps with LEAD, islands with DENSE_RANK, local days, tolerance.
Two questions with the same shape
Hansini runs reporting for the help desk at Belgavi's Book Store. Two requests arrived in the same week. The first: for each queue, what is the longest run of consecutive days on which it had any activity, and when did each run start and end? The second, from finance: which invoice numbers are missing from the sequence?
Both are gaps-and-islands problems. An island is a maximal run of consecutive values; a gap is the space between two islands. Window functions solve both in a single pass over sorted data, without loops or self-joins. They also fail in quiet ways when the data has duplicates, time zones or several groups mixed together, and those failures produce plausible numbers rather than errors.
This article builds the standard queries, measures them in SQLite 3.49 from Python's standard library, shows the PostgreSQL form, and then works through the inputs that break them. The companion checks every query against a brute-force reference over hundreds of generated tables.
Missing numbers: gaps with LEAD
Gaps are the easier half. Sort the numbers, look at the next one with LEAD, and keep pairs that are more than one apart.
SELECT invoice_no + 1 AS first_missing, next_no - 1 AS last_missing
FROM (SELECT invoice_no, LEAD(invoice_no) OVER (ORDER BY invoice_no) AS next_no
FROM invoices)
WHERE next_no - invoice_no > 1
ORDER BY first_missing;For invoices 1001, 1002, 1003, 1006, 1007, 1010, 1011 and 1012 this returns two gaps: 1004 to 1005 and 1008 to 1009. The last row has no next number, next_no is NULL, the comparison is unknown and the row drops out, which is what you want. Gaps before the first or after the last number need the expected range from elsewhere, for example the previous month's last invoice.
Consecutive days: the value minus row number trick
For islands, the classic technique subtracts a row number from the value. Within a run of consecutive days, the day and the row number both increase by one per row, so their difference is constant. When a day is skipped, the day jumps by two while the row number still increases by one, and the difference changes. The difference is therefore an island key.
| Day | Row number | Day minus row number | Island |
|---|---|---|---|
| 1 October | 1 | 30 September | A |
| 2 October | 2 | 30 September | A |
| 3 October | 3 | 30 September | A |
| 5 October | 4 | 1 October | B |
| 6 October | 5 | 1 October | B |
In SQL, group by the key and take the minimum and maximum day:
WITH k AS (
SELECT queue, day,
day - ROW_NUMBER() OVER (PARTITION BY queue ORDER BY day) AS island_key
FROM queue_days)
SELECT queue, MIN(day) AS start_day, MAX(day) AS end_day, COUNT(*) AS days
FROM k
GROUP BY queue, island_key
ORDER BY queue, start_day;The query assumes queue_days has exactly one row per queue and day. In SQLite the companion stores days as integers (days since 1 October 2026); in PostgreSQL, subtracting an integer from a date gives a date, so day - ROW_NUMBER() OVER (...)::int works directly.
Failure one: repeated days
Real activity tables do not have one row per day; they have one row per event. If the query runs over raw events, a day with two rows gets two row numbers. The row number then advances by two while the day advances by zero and then one, and the island key shifts in the middle of what should be one run.
The companion's duplicates_row_number preset makes this concrete: 30 days, one queue, 24 rows of which 4 fall on a day that already has a row. The reference finds 9 islands with a longest run of 5 days. ROW_NUMBER over the raw rows also finds 9 islands, but 5 of them are wrong, and one spans 13 days from 18 October to 30 October because the split pieces of separate runs line up on the same key. The longest-run figure, the number a dashboard would show, is more than double the truth.
Two fixes give the right answer, and the companion checks both:
DENSE_RANKassigns the same rank to equal days, so duplicates no longer advance the counter:day - DENSE_RANK() OVER (PARTITION BY queue ORDER BY day).SELECT DISTINCTfirst, thenROW_NUMBERover the distinct days. Join back to the raw rows if you need counts per island.
Failure two: which day is it
An event logged at 21:40 UTC on 3 October happened on 4 October in Bengaluru (UTC+05:30). If the help desk works in India, the activity day is the local date, and grouping by the UTC date puts some events on the wrong day.
The local_day_offset preset logs 30 percent of events between 20:00 and 23:59 UTC and buckets them at UTC+05:30. Eight of 22 rows land on a different day than their UTC date, and the reference finds 9 islands by local day against 7 by UTC day. Neither number is wrong in itself; they answer different questions. The bug is computing one and reporting it as the other. Moving events also creates new duplicate days: four rows in that preset share a local day with another row, even though no duplicates were generated, which is a second reason to use DENSE_RANK or DISTINCT.
In PostgreSQL, convert explicitly before taking the date, with a real zone name so that daylight-saving changes are handled:
SELECT queue, (created_at AT TIME ZONE 'Asia/Kolkata')::date AS day
FROM case_events;The companion uses a fixed offset because it has no time zone database; real zones with daylight saving need one.
Failure three: forgetting the partition
Without PARTITION BY queue, all queues share one sequence of days. Two queues that are each active every other day become one queue active every day. The two_queues_not_partitioned preset returns 5 islands where the per-queue reference has 15. When a dashboard shows one number per queue but the query never partitioned, the numbers are combinations of other queues' activity.
Allowing a missing day
Sometimes a one-day gap should not break a run: a queue that is closed on Sundays still has a "continuous" run of activity. The row-number trick cannot express a tolerance, because any gap changes the key. A different formulation can: mark where an island starts with LAG, then number the starts with a running SUM.
WITH f AS (
SELECT queue, day,
CASE WHEN LAG(day) OVER w IS NULL OR day - LAG(day) OVER w > 1 + :tolerance
THEN 1 ELSE 0 END AS starts
FROM queue_days
WINDOW w AS (PARTITION BY queue ORDER BY day)),
k AS (
SELECT queue, day,
SUM(starts) OVER (PARTITION BY queue ORDER BY day
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS island_key
FROM f)
SELECT queue, MIN(day), MAX(day), COUNT(DISTINCT day)
FROM k GROUP BY queue, island_key;With a tolerance of one day, the tolerance_one_day preset merges 7 islands into 2, and the longest run becomes 22 days. Report both the span of the island and the number of active days in it; with a tolerance they differ. Repeated days are harmless here: a row on the same day as the previous row never starts an island, so it always joins the current one. With a tolerance of zero this query gives the same islands as the DENSE_RANK version, and the companion checks that too.
Testing island queries
Island queries are easy to get almost right, so test them against a dumb reference rather than against expected numbers you worked out by hand:
- Write a brute-force reference. Sort each group's distinct days and split wherever the gap exceeds one day plus the tolerance. The companion's reference is ten lines of Python.
- Generate many tables. The companion sweeps 24 seeds, every method, partitioned and not, with duplicates, late events and two different offsets, and asserts that SQLite's output equals the model.
- Include the hostile cases on purpose: repeated days, events near midnight, a single-day island, an empty group, two groups that interleave.
- Check the summary numbers a dashboard uses, such as the longest run, not only the list of islands.
Performance notes
All of these queries sort each partition once. An index on (queue, day), or on (queue, created_at) for the event table, lets the database read rows in order instead of sorting them. Materialising a one-row-per-day table (a daily rollup) makes the queries smaller and the duplicate problem disappear, at the cost of keeping the rollup up to date when late events arrive.
Limits
The examples are synthetic: one or two queues, a month or a quarter of days and seeded activity. SQLite 3.49.1 was used for every measurement; window functions require SQLite 3.25 or newer. The PostgreSQL statements follow the documented syntax but were not run for this article.
Interactive experiment
Gaps and islands: consecutive runs, duplicates and a tolerance. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.