← Back to SQL, page 21

sql-0420 · Hard senior

Merge overlapping or touching booking intervals into continuous blocks.

Sort intervals by start, and mark a new block whenever an interval starts after the latest end seen so far. A running maximum of end over the previous rows gives that latest end, a running sum of the new-block flags numbers the blocks, and grouping by that number yields each block's MIN(start) and MAX(end).

Full answer
sql
CREATE TABLE busy (id INTEGER PRIMARY KEY, s INTEGER, e INTEGER);
INSERT INTO busy VALUES (1, 1, 4), (2, 3, 6), (3, 6, 8), (4, 10, 12), (5, 11, 11), (6, 15, 18);
sql
WITH flagged AS (
  SELECT s, e, CASE WHEN s <= MAX(e) OVER (ORDER BY s, e ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) THEN 0 ELSE 1 END AS new_block FROM busy
), numbered AS (
  SELECT s, e, SUM(new_block) OVER (ORDER BY s, e ROWS UNBOUNDED PRECEDING) AS block FROM flagged
)
SELECT block, MIN(s) AS block_start, MAX(e) AS block_end FROM numbered GROUP BY block ORDER BY block;
blockblock_startblock_end
118
21012
31518

Intervals 1 to 3 chain together, because 3 starts before 4 ends and 6 starts exactly where the previous one ends, so they form block 1 from 1 to 8. Interval 5 lies inside interval 4, giving block 2 from 10 to 12, and interval 6 stands alone. The running maximum is essential: comparing only with the previous row's end would wrongly split a block when a long interval covers several short ones. Using <= treats touching intervals as one block; change it to < to keep them apart. The first row has no previous rows, so its MAX is NULL and the CASE starts a new block.

sql
CREATE TABLE busy (id INTEGER PRIMARY KEY, s INTEGER, e INTEGER);
INSERT INTO busy VALUES (1, 1, 4), (2, 3, 6), (3, 6, 8), (4, 10, 12), (5, 11, 11), (6, 15, 18);

WITH flagged AS (
  SELECT s, e, CASE WHEN s <= MAX(e) OVER (ORDER BY s, e ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) THEN 0 ELSE 1 END AS new_block FROM busy
), numbered AS (
  SELECT s, e, SUM(new_block) OVER (ORDER BY s, e ROWS UNBOUNDED PRECEDING) AS block FROM flagged
)
SELECT block, MIN(s) AS block_start, MAX(e) AS block_end FROM numbered GROUP BY block ORDER BY block;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Running MAX of previous ends detects overlaps
  • Running SUM of flags numbers blocks
  • Group by block for start and end
  • <= merges touching intervals

Common mistakes

  • Comparing only with the previous row's end
  • Forgetting contained intervals

Follow-ups

  • How would you compute total busy time?
  • How would you find free gaps between blocks?

Tips

  • Explain why the running maximum matters