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;
If the sequence of IDs is: 1,2,3,6,7,8, then it will correctly return 4 as the result.
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?