views:

42

answers:

3
+3  Q: 

MySQL id sequence

Is this a correct way for id generation in MySQL ?

INSERT INTO Picture (PictureId,First_pick,Title,Description,File_Name,Is_Vertical)VALUES
((SELECT max(pictureid)+1 FROM Picture),0,?,?,?,?)

I mean if it is guaranted that PictureId will be unique when this query is run by many threads ?

I can't modify table structure. Should I use any specific locks, index or transaction isolation level ?

Regards, Michal

+3  A: 

You would usually use an AUTO_INCREMENT field that will take care of those things for you: Manual

But the question is good nevertheless, I would like to hear a deep answer from a mySQL expert on this. How reliable would it be to do it in the described way?

Pekka
Thanks. I know about AUTO_INCREMENT but I'd rather not modify the table structure.
Michał Fronczyk
A: 

If you really cannot use an AUTO_INCREMENT then you should definitely lock the table for writing.

extraneon
But is it possible that MySQL does some index locking when the inner SELECT is executed ? These queries are executed in one transaction. (I use InnoDB)
Michał Fronczyk
+2  A: 

Unless you've locked the table adequately - which could cause problems by preventing other threads from accessing it - your proposed approach would be susceptible to race conditions if multiple threads attempt to insert records simultaneously.

Dave Sherohman