Trying to determine the next ID is inviting race conditions. The next available ID is shared data which can change at any time.
Consider two database connections working on the same table simultaneously. max(id)
is 9.
| A B
| id = get_next_id(some_table) # 10
t id = get_next_id(some_table) # 10
i
m # Success
e insert into some_table (id) values (id)
| # Failure
V insert into some_table (id) values (id)
Both ask for the next ID and get the same value. Both try to insert the same ID. One succeeds, the other fails.
You can try to patch this up with locks, transactions, sequence tables... but you'd be reimplementing auto_increment poorly.
Use auto_increment
. If you want a specific ID, pass it in explicitly. Though note that this will cause the ID to increment from there. This is correct behavior to avoid ID conflicts.
-- Auto increment ID
insert into some_table (foo, bar) values (23, 42);
-- Explicit ID
insert into some_table (id, foo, bar) values (99, 23, 42);
insert into some_table (foo, bar) values (13, 44); -- ID is 100
If you want to know the next ID, you can check the information_schema
table.
SELECT `AUTO_INCREMENT`
FROM `information_schema`.`TABLES`
WHERE `TABLE_SCHEMA` = ‘yourDatabaseName’
AND `TABLE_NAME` =’yourTableName';
But it's difficult to think of a case when you need to know the next ID that isn't a symptom of a poor design.
A good schema design doesn't care what the next ID is, just that it is a unique identifier. You can use UUID primary keys. Then there is no "next" key.
create table people (
id binary(16) primary key default (uuid_to_bin(uuid())),
name varchar(255)
);
insert into people (name) values ('Yarrow Hock'), ('Che Guvera');
select * from people;
+------------------------------------+-------------+
| id | name |
+------------------------------------+-------------+
| 0x8A501F549CA611EA91B96B65B86DF892 | Yarrow Hock |
| 0x8A50240E9CA611EA91B96B65B86DF892 | Che Guvera |
+------------------------------------+-------------+
You can use the default generated by MySQL, or you can pass your own in.