V
V
vetsmen2017-09-18 15:22:49
MySQL
vetsmen, 2017-09-18 15:22:49

Can 2 queries run at the same time?

There is a piece of function code:

var updater = function() {
mysql.query('SELECT balance FROM Users WHERE id = 5').then(function(balance){
   if(balance < 100) {
      return;
   }
   mysql.query('UPDATE Users SET balance = balance - 100 WHERE id = 5').then(function(res){
      return;
   });
});
}

If this function is called 2 times in a row, is it possible that the update request will not be completed in time and the check will not work the second time?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2017-09-18
@vetsmen

And why not write one request and not take a steam bath about whether it will have time to be executed there or not? Something like this:

UPDATE Users SET
  balance = balance - 100
WHERE id = 5 AND balance >= 100

I
Ilya Gerasimov, 2017-09-18
@Omashu

yes, such a situation may be, in your case you have already been offered a solution by simplifying the query, but there are other cases in which it is worth using sql transactions, correctly hanging unique indexes so that there are no duplicates with conflicting queries

N
Nikolai Konyukhov, 2017-09-18
@heahoh

SELECT ... FOR UPDATE

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question