Results 1 to 3 of 3
Dec 24, 2012, 07:33 #1
- Join Date
- Jun 2012
- London, United Kingdom, United Kingdom
- 0 Post(s)
- 0 Thread(s)
Finding missing numbers in a sequence prior to first existing number
I have been using this (well circulated) method to ascertain the first missing number in a sequence from a selection of IDs from a specific column (‘song_name’) in a table (‘song’) so as to reassign deleted IDs to future entries (these field names are just examples):-
SELECT l.id+1 AS start FROM (SELECT id FROM song WHERE song_name LIKE ‘imagine’) AS l LEFT OUTER JOIN (SELECT id FROM song WHERE song_name LIKE ‘imagine’) AS r ON l.id+1 = r.id WHERE r.id IS NULL ORDER BY start ASC LIMIT 1;Code:
ID SONG 1 Imagine 2 Imagine 3 Imagine 6 Imagine 7 Imagine 8 Imagine 1 Eleanor Rigby 2 Eleanor Rigby 3 Eleanor Rigby
However, if the sequence is: 2,3,6,7,8, then it will still return 4 as the result, even though 1 is the first missing number (it only finds the first missing number from after the sequence starts, i.e. if the sequence is 50,51,52,54,55, then the result would be 53, disregarding the missing IDs of 1 to 49).
My solution to this would be to first run a separate command to check specifically if 1 is found in the selected IDs, and if not then assign 1 as the ID. But if 1 is found, then run the above command, as any gap in the sequence following 1 would definitely be the first.
But I am wondering if there is a more elegant solution that I have not thought of? Perhaps using the WHERE EXISTS / WHERE NOT EXISTS command?