Is incrementing a field in MySQL atomic?

落爺英雄遲暮 提交于 2019-11-27 07:14:13

MyISAM tables use table level locking. This means that the whole table will be locked during the execution of your update query. So the answer for your simplified use case is: yes, this is thread safe. But this may not be the case if you use another storage engine or your update includes multiple tables.

Here is a quote from the MySQL manual for more clarity:

Table locking enables many sessions to read from a table at the same time, but if a session wants to write to a table, it must first get exclusive access. During the update, all other sessions that want to access this particular table must wait until the update is done.

You can also consider using auto increment columns, transactions or external synchronization if that fits to your design.

Cheers!

TraderJoeChicago

The write is atomic but an increment also requires a read. So the question is: Are you sure the read is safe, in other words, are you sure another thread doing the increment will not end up with the same value to be incremented? I have doubts. The 100% correct way of doing this would be.

-- begin transaction here

select counter from myCounters where counter_id = 1 FOR UPDATE;

-- now the row is locked and nobody can read or modify its values

update myCounters set counter = ? where id = 1;

-- set ? to counter + 1 programmatically

commit; -- and unlock...

Yes, the table (or rows in InnoDB format databases) is automatically locked when you execute an update query.

This form of UPDATE is atomic. Other forms of UPDATE can be made atomic by using transactions with SELECT ... FOR UPDATE.

Had the same issue, although query was more complicated:

UPDATE CLB_SYNC_T SET PENDING_MESSAGES = PENDING_MESSAGES + ? WHERE USER_ID = ?

Using MyISAM as a default engine did not help, so I fallback to SELECT FOR UPDATE use.

With SELECT FOR UPDATE performance improved ~ 10 times, since MySQL did not lock whole table, to make a row update.

Another approach when using InnoDB is using unique index on multiple column as follow:

Table 'Sessions' { unique_key(browser_session_id,profile_id) // ensures that inserting 1 entry per session will occur once }

select count(browser_session_id) from Sessions

Will guarantee result of unique sessions, as multiple sessions per user is not allowed.

Conclusions

  • Advantage

    Each insert does require a pre-select.

  • Disadvantage

    It is not suitable for all cases.

    May slow down write performance, and requires extra management

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!