
PUZZLE 57 GAPS—VERSION ONE 227
PUZZLE
57 GAPS—VERSION ONE
This is a classic SQL programming problem that comes up often in
newsgroups. In the simplest form, you have a table of unique numbers
and you want to either find out if they are in sequence or find the gaps in
them. Let’s construct some sample data.
CREATE TABLE Numbers (seq INTEGER NOT NULL PRIMARY KEY);
INSERT INTO Numbers
VALUES (2), (3), (5), (7), 8), (14), (20);
Answer #1
Finding out if you have a sequence from 1 to (n) is very easy. This will
not tell you where the gaps are, however.
SELECT CASE WHEN COUNT(*) = MAX(seq)
THEN 'Sequence' ELSE 'Not Sequence' END FROM Numbers;
The math ...