B
B
bezdealnick2018-04-23 12:26:19
MySQL
bezdealnick, 2018-04-23 12:26:19

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

With blocking, we first block the record, reduce the balance without `balance` >= 150, with such a request:
update `users` set `balance` = `balance` - 150 where `id` = 54

After decreasing, we remove the blocking.
Entries in table 481k.
Which query will work faster? Or does it not make much sense to change one to the other?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Entelis, 2018-04-23
@DmitriyEntelis

START TRANSACTION;
select * from users where id = 54 FOR UPDATE
//проверка бизнес логики на наличие денег
update `users` set `balance` = `balance` - 150 where `id` = 54;
COMMIT;

The query "where `id` = 54 and `balance` >= 150" is dangerous.
Innodb does not lock specific records, but index ranges - with such a request, all records with a balance >= 150 will be locked, with all the consequences.

R
Rsa97, 2018-04-23
@Rsa97

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 question

Ask a Question

731 491 924 answers to any question