Does “select for update” prevent other connections inserting when the row is not present

前端 未结 5 1067
轮回少年
轮回少年 2020-12-30 21:24

I\'m interested in whether a select for update query will lock a non-existent row.

e.g.

Table FooBar with two columns, foo and bar, foo has a un

5条回答
  •  执念已碎
    2020-12-30 22:17

    On Oracle:

    Session 1

    create table t (id number);
    alter table t add constraint pk primary key(id);
    
    SELECT *
    FROM t
    WHERE id = 1
    FOR UPDATE;
    -- 0 rows returned
    -- this creates row level lock on table, preventing others from locking table in exclusive mode
    

    Session 2

    SELECT *
    FROM t 
    FOR UPDATE;
    -- 0 rows returned
    -- there are no problems with locking here
    
    rollback; -- releases lock
    
    
    INSERT INTO t
    VALUES (1);
    -- 1 row inserted without problems
    

提交回复
热议问题