Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-increment the primary key without setting the identity

Tags:

sql

I am using the following syntax to insert new records (I don't want to have duplicate keys):

insert into tbl(key) values select max(key)+1 from tbl

Someone says it will have concurrency problem.
Is that right?

SELECT -> LOCK table -> INSERT

or

LOCK table -> SELECT -> INSERT

Which one of the above is correct?

like image 415
Billy Avatar asked Dec 29 '25 15:12

Billy


1 Answers

If this happens inside a transaction you will be fine.

like image 104
Adriaan Stander Avatar answered Jan 01 '26 05:01

Adriaan Stander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!