I have a table v_ext in a MySQL with InnoDB engine:
- id: primary key
- code: pre-generated list of codes (say 1000 codes are generated randomly)
- user_id: initially NULL
When a user purchase an item, they receive a code. I need to update the table to populate the user_id column. I have two options:
START TRANSACTION;
SELECT id FROM v_ext WHERE user_id IS NULL LIMIT 1 FOR UPDATE; -- return id 54 for ex.
UPDATE v_ext SET user_id=xxx WHERE id=54;
COMMIT;
or
UPDATE v_ext SET user_id=xxx WHERE user_id IS NULL LIMIT 1;
Is the second option safe if I have thousands of users purchasing at the same time? If so, is it correct to assume this second option is better for performance since it needs only one query?
UNIQUE
constraint onuser_id
? (i.e. can a user only have one code)? – AugustusaugyEXISTS
would be a better use in terms of concurrency and performance. – VulcanUPDATE v_ext SET user_id=xxx WHERE EXISTS (SELECT * FROM v_ext WHERE user_id IS NULL LIMIT 1)
? – DownbeatUPDATE v_ext SET user_id=xxx WHERE EXISTS (SELECT * FROM v_ext WHERE ID = 54 AND user_id IS NULL)
but I believe more seasoned experts here could provide you with a better answer to compare which would be best in your case :) +1 for the interesting question focusing on performance. – VulcanID
as a variable in that case. Eager to know the outcome of this question. – VulcanYou can't specify target table for update in FROM clause
. I am going to benchmark my two options and post the results – Downbeat