The purpose of AUTO_INCREMENT
is to generate simple, unique and meaningless identifiers for your strings. As soon as you plan to reuse these identifiers, they are no longer unique (at least not in time), so I get the impression that you are not using the right tool for the job. If you decide to get rid of AUTO_INCREMENT
, you can do all your inserts with the same algorithm.
As in SQL code, this query will match existing rows with rows that have the following identifier:
SELECT a.foo_id, b.foo_id FROM foo a LEFT JOIN foo b ON a.foo_id=b.foo_id-1
eg:.
1 NULL 4 NULL 10 NULL 12 NULL 17 NULL 19 20 20 NULL 24 25 25 26 26 27 27 NULL
Therefore, it is easy to filter the lines and get the first space:
SELECT MIN(a.foo_id)+1 AS next_id FROM foo a LEFT JOIN foo b ON a.foo_id=b.foo_id-1 WHERE b.foo_id IS NULL
Take this as a starting point because it still needs some tweaking:
- You need to consider the case where the lowest available number is the lowest.
- You need to lock the table to handle parallel inserts.
- On my computer, it is slow as hell with large tables.
source share