My goal is to insert a new and unique(unique is very important) number into a MySQL table on the server every time upon an event on a user’s machine, using ajax.
So, server’s part on user’s event is doing this (using php):
- Finds a maximum value from the column in the db,
- Adds 10 to a maximum value,
- this is a new and unique (bigger than a maximum) value, we insert insert into a table.
Will all numbers be unique and go like 1, 11, 21, 31, if it starts from 1? I’m curious if inserting into the Table finishes before it starts performing another queue and coule be like 1, 11, 21, 21, 31, 41?
If it theoretically works like this (ordered by time)
- find max value from the column for the first user
- find max a value from the column for the second user (it will be the same)
- insert a (max+10) for the first user into the same table
- insert a (max+10) for the second user into the same table (it will be the same), then the results will be the same, and 1 value could be repeated twice or even more…
So, the question is: will all numbers be 100% unique?
Depending on this I have to choose which algorithm to use for creating unique numbers.
Added:
Is it possible to be sure with this algorythm and without using autoincrements? Autoincrement is used for another column. Holes between numbers are OK. The only requirement is that numbers should be different, but with some “delta” that is more than one. Sorry I didn’t notice about that in my question. Thank you.
Unless you have a very specific reason against it, I recommend using AUTO_INCREMENT – it will scale much better and actually leave fewer “holes” in the sequence of numbers than your approach.
And you are correct – your approach will not actually guarantee uniqueness in concurrent environment. One way to make your algorithm work is to have a UNIQUE constraint on your field (if it is not already PRIMARY KEY) and then repeatedly attempt to insert a new value – if it fails just generate a new value and try again and it will eventually succeed.