Full answer
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);sql
WITH k AS (
SELECT day, julianday(day) - ROW_NUMBER() OVER (ORDER BY day) AS grp FROM daily_sales
)
SELECT MIN(day) AS start_day, MAX(day) AS end_day, COUNT(*) AS days
FROM k GROUP BY grp ORDER BY start_day;| start_day | end_day | days |
|---|---|---|
| 2026-03-01 | 2026-03-03 | 3 |
| 2026-03-05 | 2026-03-06 | 2 |
| 2026-03-09 | 2026-03-09 | 1 |
The grp value is the same for every day in a streak. 1 to 3 March form one island, 5 to 6 March another, and 9 March stands alone.
Seeing the intermediate column makes the trick clear:
sql
SELECT day, ROW_NUMBER() OVER (ORDER BY day) AS rn,
julianday(day) - ROW_NUMBER() OVER (ORDER BY day) AS grp
FROM daily_sales ORDER BY day;| day | rn | grp |
|---|---|---|
| 2026-03-01 | 1 | 2461099.5 |
| 2026-03-02 | 2 | 2461099.5 |
| 2026-03-03 | 3 | 2461099.5 |
| 2026-03-05 | 4 | 2461100.5 |
| 2026-03-06 | 5 | 2461100.5 |
| 2026-03-09 | 6 | 2461102.5 |
The days jump from 3 to 5 March while the row number moves by one, so the key changes exactly where the streak breaks. The same idea works for any sequence that should increase by a fixed step, such as ticket numbers or minute buckets.
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
WITH k AS (
SELECT day, julianday(day) - ROW_NUMBER() OVER (ORDER BY day) AS grp FROM daily_sales
)
SELECT MIN(day) AS start_day, MAX(day) AS end_day, COUNT(*) AS days
FROM k GROUP BY grp ORDER BY start_day;
SELECT day, ROW_NUMBER() OVER (ORDER BY day) AS rn,
julianday(day) - ROW_NUMBER() OVER (ORDER BY day) AS grp
FROM daily_sales ORDER BY day;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- date minus ROW_NUMBER is constant within a consecutive run
- Group by that key to get each island
- MIN, MAX and COUNT describe each streak
- Works for any fixed-step sequence
Common mistakes
- Using LAG alone and struggling to label whole islands
- Forgetting to deduplicate dates before numbering
Follow-ups
- How would you compute islands per user?
- How would you find the longest streak?
Tips
- Show the intermediate key