7

Can the DEFERRABLE be used in a trigger ?

And how does the concept of DEFERRABLE works ?

It's during the whole transaction then it checks the constraint at the end of all the operations ?

1
  • It seems this is a zombie question that can't be closed as Unclear due to the open bounty, but can't be answered due to the lack of information. Flagged for moderator. idownvotedbecau.se/beingunresponsive Commented Apr 1, 2018 at 9:59

1 Answer 1

7

It looks like you mean PostgresSql. The concept of a DEFERRABLE CONSTRAINT is one which may be temporarily invalidated during the course of a transaction (with the SET CONSTRAINTS ... DEFERRED; command), but the constraints must again be valid by the time the transaction is committed.

For example, below, there is a FOREIGN KEY constraint enforcing referential integrity from Table2.Table1ID to Table1.ID:

CREATE TABLE Table1
(
  ID INT NOT NULL,
  Name VARCHAR(50),
  CONSTRAINT PK_Table1 PRIMARY KEY(ID)
);

CREATE TABLE Table2
(
  ID INT NOT NULL,
  Table1ID INT NOT NULL,
  Name VARCHAR(50),
  CONSTRAINT PK_Table2 PRIMARY KEY(ID),
  CONSTRAINT FK_Table2_Table1 FOREIGN KEY(Table1ID) REFERENCES Table1(ID) DEFERRABLE
);

Normally, the below insert would fail, if there is no row with Table1.ID = 2:

INSERT INTO TABLE2(ID, Table1Id, Name) VALUES (2, 2, 'Foreign Key Violation');

However, because the CONSTRAINT is defined as DEFERRABLE (and we've allowed deferred constraints in the transaction, below), it means we may temporarily violate the constraint, provided that the constraint is met by the time the transaction is committed. In the example below, we address the foreign key violation by inserting an additional row into table 1 to pacify the referential integrity constraint.

BEGIN TRANSACTION;
SET CONSTRAINTS ALL DEFERRED;
INSERT INTO Table2(ID, Table1Id, Name) VALUES (2, 2, 'Foreign Key Violation Allowed');
INSERT INTO Table1(ID, Name) VALUES (2, 'Fix the Violation');
COMMIT TRANSACTION;

SqlFiddle of a DEFERRED RI insert here

With regards to Triggers, DEFERRED can only be used with CONSTRAINT TRIGGERS, but the same principal above applies.

Sign up to request clarification or add additional context in comments.

3 Comments

Oracle also supports deferred constraints not inly Postgres
Yup - OP didn't tag any RDBMS originally, then stated PostGres although contradicted by mentioning SqlPlus. Although tags have been changed, OP hasn't clarified, So I guess we are all still none the wiser :(
The behaviour of deferrable constraints is pretty much the same between Oracle and Postgres (not PostGres btw)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.