I have to find the next available id (if there are 5 data in database, I have to get the next available insert place which is 6) in a MySQL database. How can I do that? I h
If you want to select the first gap, use this:
SELECT @r
FROM (
SELECT @r := MIN(id) - 1
FROM t_source2
) vars,
t_source2
WHERE (@r := @r + 1) <> id
ORDER BY
id
LIMIT 1;
There is an ANSI
syntax version of the same query:
SELECT id
FROM mytable mo
WHERE (
SELECT id + 1
FROM mytable mi
WHERE mi.id < mo.id
ORDER BY
mi.id DESC
LIMIT 1
) <> id
ORDER BY
id,
LIMIT 1
however, it will be slow, due to optimizer bug in MySQL
.