I was reviewing a Drupal module when I found this pattern for getting the id of the row last inserted:
SELECT MAX(id) FROM ... WHERE ...
where the id is a field working in a usual autoincrement way.
Is this conceptually right to do? Is there any situation when this pattern will fail in a MySQL/PostgreSQL environment?
Edit:
Thanks for the excellent comments and answers!
I should clarify my question: I meant a situation where someone would like to find out the id of the last inserted row regardless of the session.
This seems subjective, but I would say no, it’s not conceptually right, because:
idvalueYes, there is some relationship between max id and most recent insert, but consider the following:
Answer on MySQL: you get different results. Note that there doesn’t even have to be multithreading or multiple processes for this to fail. That’s because they’re two different things (which admittedly can often produce the same results).
vs
(Guess which one is right.)
@Dems pointed out that the OP is ambiguous. I’ll clarify my main point:
We’re talking about three different pieces of information:
idvalueidof row most recently inserted, specific to a sessionidof row most recently inserted into table (regardless of session)The dangerous thing is that sometimes, querying for one will give the right answer for another — but not always.