SET CONSTRAINTS ALL DEFERRED not working as expect

2019-02-16 11:36发布

If I define tables a and b as follows:

CREATE TABLE a(i integer);
ALTER TABLE a ADD CONSTRAINT pkey_a PRIMARY KEY (i);
CREATE TABLE b(j integer);
ALTER TABLE b add CONSTRAINT fkey_ij FOREIGN KEY (j)
      REFERENCES a (i) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE;
INSERT INTO a(i) VALUES(1);

And then do the following:

START TRANSACTION;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO b(j) VALUES(2);
INSERT INTO a(i) VALUES(2);
COMMIT;

It produces the error below. Why is SET CONSTRAINTS not having the desired effect?

ERROR: insert or update on table "b" violates foreign key constraint "fkey_ij"
SQL state: 23503 Detail: Key (j)=(2) is not present in table "a".

1条回答
Emotional °昔
2楼-- · 2019-02-16 12:23

For starters, only DEFERRABLE constraints can be deferred.

But that won't help your case because, FK constraints cannot be bent this way at all. Per documentation:

Referential actions other than the NO ACTION check cannot be deferred, even if the constraint is declared deferrable.

Reverse the sequence of your INSERT statements.

Related:

查看更多
登录 后发表回答