Answer the question
In order to leave comments, you need to log in
Which sql query will run faster?
Hello. There is an application, we are trying to increase the speed of work in some sections. At the moment, we use locks to reduce the balance of people, but I read that you can do this without using a lock by shifting everything to mysql by writing this query:
update `users` set `balance` = `balance` - 150 where `id` = 54 and `balance` >= 150
`balance` >= 150
, with such a request:update `users` set `balance` = `balance` - 150 where `id` = 54
Answer the question
In order to leave comments, you need to log in
START TRANSACTION;
select * from users where id = 54 FOR UPDATE
//проверка бизнес логики на наличие денег
update `users` set `balance` = `balance` - 150 where `id` = 54;
COMMIT;
That one request, that the other is atomic (with AUTOCOMMIT = 1) and their execution does not intersect with other requests. No additional blocking is required for them, the speed of queries with a unique `id` will be almost the same.
Locking is required if you first receive the balance (SELECT), then check the possibility of debiting funds, and only then write them off (UPDATE). In this case, you need to lock the table or row so that during the check there is no write-off of funds by another thread.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question