When to use SELECT … FOR UPDATE?

前端 未结 2 1817
离开以前
离开以前 2020-11-28 17:51

Please help me understand the use-case behind SELECT ... FOR UPDATE.

Question 1: Is the following a good example of when SELECT .

2条回答
  •  盖世英雄少女心
    2020-11-28 18:29

    Short answers:

    Q1: Yes.

    Q2: Doesn't matter which you use.

    Long answer:

    A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

    Another way of looking at it, it is as if the following two statements are executed atomically:

    select * from my_table where my_condition;
    
    update my_table set my_column = my_column where my_condition;
    

    Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

    Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

    What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.

提交回复
热议问题