0

Say two users are using a website and an operation within that website inserts a new row, then selects that row (by selecting the most recently inserted row) to be returned to the user. Is there a chance that in the time between one user having a row inserted and having the row selected that the other user could insert a new row, thus making the select query select the other user's row rather than the correct one. If so is there any way to combat this?

user3887706
  • 23
  • 1
  • 3
  • 1
    of course they can interfere with each other, if you are picking the "last inserted row". You should instead use their id's(which are unique) for this kind of queries – epipav Aug 23 '14 at 13:02
  • 2
    Without seeing the code you're using to tell if you're doing something dumb to get the row, the only answer you can get is "yes, it's possible to write bad code that does bad things." – Wooble Aug 23 '14 at 13:03
  • Which is why you need [`LAST_INSERT_ID()`](http://stackoverflow.com/questions/3837990/last-insert-id-mysql/3838011#3838011) – Clockwork-Muse Aug 24 '14 at 05:28

1 Answers1

1

If by "most recently inserted row" you mean something like:

select id
from table t
order by id desc
limit 1;

Then they can definitely interfere with each other.

If by "most recently inserted row" you mean LAST_INSERTED_ID(), then you are safe. This is stored on a per-connection basis. You can read more about it here.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786