SELECT vs UPDATE performance with index

后端 未结 7 1738
有刺的猬
有刺的猬 2020-12-09 04:10

If I SELECT IDs then UPDATE using those IDs, then the UPDATE query is faster than if I would UPDATE using the conditions

7条回答
  •  一向
    一向 (楼主)
    2020-12-09 04:44

    The accepted answer seems right but is incomplete, there are major differences.

    As much as I understand, and I'm not a SQL expert:

    The first query you SELECT N rows and UPDATE them using the primary key.
    That's very fast as you have a direct access to all rows based on the fastest possible index.

    The second query you UPDATE N rows using LIMIT That will lock all rows and release again after the update is finished.

    The big difference is that you have a RACE CONDITION in case 1) and an atomic UPDATE in case 2)

    If you have two or more simultanous calls of the case 1) query you'll have the situation that you select the SAME id's from the table. Both calls will update the same IDs simultanously, overwriting each other. This is called "race condition".

    The second case is avoiding that issue, mysql will lock all rows during the update. If a second session is doing the same command it will have a wait time until the rows are unlocked. So no race condition is possible at the expense of lost time.

提交回复
热议问题