MySQL Forums
Forum List  »  Newbie

How to prevent a SELECT from reading after another transaction is done?
Posted by: Ariel Arelovich
Date: November 13, 2019 04:47AM

Here is the thing. I need to insert a row into a table but ONLY if the number of rows is less than 10.

Normally I do this by:
1) SELECT COUNT(*) FROM mytable WHERE cDate = '2019-01-01';
2) Check that the return value is less than 10. If not, then I need to return a message to the user.
3) If it is less than 10. I do INSERT INTO mytable (cDate) VALUE ('2019-01-01').


Now this is running in a server and the table has 9 rows. So if while I'm doing the check on the number of rows, ANOTHER user does the same check it will again return 9 rows (because the INSERT has not happened yet). This will result in two inserts giving a total of 11 rows where the maximum allowed is 10.

How can I prevent this from happening?

Options: ReplyQuote


Subject
Written By
Posted
How to prevent a SELECT from reading after another transaction is done?
November 13, 2019 04:47AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.