Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more efficient method than transactions?

insert into table1 ...;
update table2 set count=count+1;

The above inserts something into table1, and if it succeeds, updates the count field of table2.

Of course this kind of thing can be handled by transactions, but transactions need to lock the table, which will be not efficient in a high concurrent system. And it can be even worse if you need to update multiple tables in that transaction.

What's your solution?

I'm using PHP, and I implement transactions this way:

mysql_query('begin');

mysql_query($statement1);

mysql_query($statement2);
...
mysql_query('commit');

So it looks like all tables referred in those $statement will be locked?

like image 248
user198729 Avatar asked Jan 18 '26 06:01

user198729


1 Answers

A transaction (which in context of MySQL assumes InnoDB) will not need to lock the whole table.

The INSERT will lock the individual row without gap locks.

The UPDATE will not lock any gaps too if you provide an equality or IN condition on an indexed field in the WHERE clause.

This means that with a properly indexed table, INSERTs will not block each other, while the UPDATEs will only block each other if they affect the same row.

The UPDATE will of course lock the individual row it affects, but since it is the last operation in your transaction, the lock will be lifted immediately after the operation is commited.

The locking itself is in fact required so that two concurrent updates will increment the counts sequentially.

like image 80
Quassnoi Avatar answered Jan 20 '26 21:01

Quassnoi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!