-2

I assign the first available row to each coming user as

SELECT id FROM table1 WHERE status IS NULL ORDER BY id LIMIT 1
fetched id is xxx
UPDATE table1 SET status='taken' WHERE id=xxx

How can I make sure that not a second user retrieve the same id before it is UPDATEd as taken?

NOTE: It has nothing to do with INSERT. The table is already there. Users should take the first available row. UPDATE is just to keep track of taken rows.

Googlebot
  • 15,159
  • 44
  • 133
  • 229

2 Answers2

1

Use transactions:

start transaction;
SELECT @A:=id FROM table1 ORDER BY id LIMIT 1
UPDATE table1 SET status='taken' WHERE id=@A
commit;
Ivanka Todorova
  • 9,964
  • 16
  • 66
  • 103
0

Transactionless version:

SELECT id FROM table1 WHERE status != 'taken' ORDER BY id LIMIT 1
fetched id is xxx
UPDATE table1 SET status='taken' WHERE id=xxx AND status != 'taken'
check number of affected rows
Alex Blex
  • 34,704
  • 7
  • 48
  • 75