user1431627
user1431627

Reputation: 815

Concurrent handling in MySQL

When updating the field like this it will lock the field:

UPDATE table SET field = field + 1

Since this is a part of a counter that is expecting a bit of a load, I am afraid not all the count will be registred when multiple users comes to my site.

Is there a better way or a fix of doing this?

Upvotes: 2

Views: 255

Answers (2)

SDwarfs
SDwarfs

Reputation: 3239

Your solution:

 UPDATE table SET field = field + 1

is absolutely perfect. That is a single SQL statement, which is fully executed without side effect or not at all. All you could additionally do is, to check weather your statement was actually executed. If not, you could retry to execute it. But there is no real reason for that. You can leave it as it is... In most cases when correctly written statements fail, there is another reason (like an overloaded DB) and retrying would make things even worse.

If you only have short write/read accesses to that table everything is fine; if concurrent commands need to access it, they will wait until the lock is freed and they will execute then.

Only if you have very time consuming operations on THAT same table that take more than 1-2 seconds to execute. Then you might loose some countings. The timeout to wait for aquiring the lock is usually something as 10 oder 30 seconds. You could also loose counts, if a process does just manually lock the table (e.g. "LOCK table") and does not free it. This would be a bug ... Other SQL statements wouldnt be able to aquire a lock and finally would be aborted after some longer waiting period.

Upvotes: 4

derki
derki

Reputation: 620

myisam engine is always locking table before executing transaction, so other concurrent transactions will be forced to wait until this one will be done

Upvotes: 5

Related Questions