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
In addition to Lukasz Lysik's answer - LEFT-JOIN kind of SQL.
As I understand, if have id's: 1,2,4,5 it should return 3.
SELECT u.Id + 1 AS FirstAvailableId
FROM users u
LEFT JOIN users u1 ON u1.Id = u.Id + 1
WHERE u1.Id IS NULL
ORDER BY u.Id
LIMIT 0, 1
Hope it will help some of visitors, although post are rather old.
Given what you said in a comment:
my id coloumn is auto increment i have to get the id and convert it to another base.So i need to get the next id before insert cause converted code will be inserted too.
There is a way to do what you're asking, which is to ask the table what the next inserted row's id will be before you actually insert:
SHOW TABLE STATUS WHERE name = "myTable"
there will be a field in that result set called "Auto_increment" which tells you the next auto increment value.
SELECT ID+1 "NEXTID"
FROM (
SELECT ID from TABLE1
WHERE ID>100 order by ID
) "X"
WHERE not exists (
SELECT 1 FROM TABLE1 t2
WHERE t2.ID=X.ID+1
)
LIMIT 1
One way to do it is to set the index to be auto incrementing. Then your SQL statement simply specifies NULL and then SQL parser does the rest for you.
INSERT INTO foo VALUES (null);
Update 2014-12-05: I am not recommending this approach due to reasons laid out in Simon's (accepted) answer as well as Diego's comment. Please use query below at your own risk.
The shortest one i found on mysql developer site:
SELECT Auto_increment FROM information_schema.tables WHERE table_name='the_table_you_want'
mind you if you have few databases with same tables, you should specify database name as well, like so:
SELECT Auto_increment FROM information_schema.tables WHERE table_name='the_table_you_want' AND table_schema='the_database_you_want';
you said:
my id coloumn is auto increment i have to get the id and convert it to another base.So i need to get the next id before insert cause converted code will be inserted too.
what you're asking for is very dangerous and will lead to a race condition. if your code is run twice at the same time by different users, they will both get 6 and their updates or inserts will step all over each other.
i suggest that you instead INSERT
in to the table, get the auto_increment value using LAST_INSERT_ID()
, and then UPDATE
the row to set whatever value you have that depends on the auto_increment value.