Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert with id in range

I have a table with unique id column being able to accept only values from 0 to 255. When rows are removed, their ids can be reused. For inserting I know I can just generate numbers in my app in a loop until succeeded but is there a better way to generate such ids at database side? How will it interact with concurrent transactions? Should I use some specific isolation level for this?

like image 487
Vlad Avatar asked Aug 13 '26 20:08

Vlad


1 Answers

To find the lowest Id to insert you can simply find the minimum value for which the next expected value does not exist

select Coalesce(Min(id), 0) + 1
from t
where not exists (select * from t t2 where t2.id = t.id + 1);
like image 167
Stu Avatar answered Aug 15 '26 09:08

Stu



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!