← Back to SQL, page 13

sql-0254 · Hard senior

Group consecutive sale dates into islands and show each streak's start, end and length.

Subtract a row number from each date: within a run of consecutive days, the date and the row number grow together, so date minus row_number is constant and identifies the island. Group by that key and take MIN, MAX and COUNT. In SQLite compute it with julianday(day) - ROW_NUMBER() OVER (ORDER BY day).

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_dayend_daydays
2026-03-012026-03-033
2026-03-052026-03-062
2026-03-092026-03-091

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;
dayrngrp
2026-03-0112461099.5
2026-03-0222461099.5
2026-03-0332461099.5
2026-03-0542461100.5
2026-03-0652461100.5
2026-03-0962461102.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