Skip to Main Content
  • Questions
  • Interdependent Foreign Key Constraints

Breadcrumb

Connor and Chris will both be at AI World from October 12 to October 17 , the premier Oracle conference of 2025. If you're in Vegas, please come say Hi or pop into our sessions

Question and Answer

Chris Saxon

Thanks for the question, Radha Sri Seshu.

Asked: July 25, 2017 - 11:16 am UTC

Last updated: July 25, 2017 - 1:24 pm UTC

Version: 11.2

Viewed 1000+ times

You Asked

SQL> CREATE TABLE A(NO1 NUMBER(2) PRIMARY KEY,NO2 NUMBER(2));

Table created.

SQL> CREATE TABLE B(NO1 NUMBER(2) PRIMARY KEY,NO2 NUMBER(2));

Table created.

SQL> ALTER TABLE A ADD CONSTRAINT AA FOREIGN KEY(NO2) REFERENCES B(NO1);

Table altered.

SQL> ALTER TABLE B ADD CONSTRAINT BB FOREIGN KEY(NO2) REFERENCES B(NO1);

Table altered.

SQL> INSERT INTO A VALUES(10,20);
INSERT INTO A VALUES(10,20)
*
ERROR at line 1:
ORA-02291: integrity constraint (SUBK.AA) violated - parent key not found


SQL> INSERT INTO B VALUES(10,20);
INSERT INTO B VALUES(10,20)
*
ERROR at line 1:
ORA-02291: integrity constraint (SUBK.BB) violated - parent key not found

and Chris said...

If you have foreign keys that form a circle you need to declare at least one of them as deferrable (initially deferred):

CREATE TABLE A(NO1 NUMBER(2) PRIMARY KEY,NO2 NUMBER(2));
CREATE TABLE B(NO1 NUMBER(2) PRIMARY KEY,NO2 NUMBER(2));

ALTER TABLE A ADD CONSTRAINT AA FOREIGN KEY(NO2) REFERENCES B(NO1);
ALTER TABLE B ADD CONSTRAINT BB FOREIGN KEY(NO2) REFERENCES B(NO1)
  deferrable initially deferred;
  
INSERT INTO B VALUES(10,20);
INSERT INTO A VALUES(20,10);

select * from a;

NO1  NO2  
20   10 

select * from b;

NO1  NO2  
10   20  


This delays validating the constraint until you commit. So if you add rows which never get a parent you'll see and error when the transaction ends:

INSERT INTO B VALUES(11,30);

commit;

ORA-02091: transaction rolled back
ORA-02291: integrity constraint (CHRIS.BB) violated - parent key not found

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Excellent

Radha Sri Seshu Kolla, July 27, 2017 - 9:23 am UTC

Thank you very much. Theoretically i know this concept, but i could not able to apply to the situation.

Thanks once again.

More to Explore

Design

New to good database design? Check out Chris Saxon's full fundamentals class.