Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding rows to table with self-referencing foreign key

I've created a table called TableTest with two columns ent and dep. ent is the primary key and dep is the foreign key which references ent. I create the table using:

CREATE TABLE TableTest (
  ent varchar(2) NOT NULL,
  dep varchar(2),
  PRIMARY KEY (ent),
  FOREIGN KEY (dep) REFERENCES TableTest(ent)
);

I must show that the three values (A1,A2,A3) depend on one another. A3 is dependent of A1 etc. However when I try to insert a row into my table such as:

INSERT INTO TableTest(ent, dep)
  VALUES ('A1','A3');

I get the following error and after doing research I'm still stuck on how to get by this. I'm very new to SQL.

ORA-02291: integrity constraint violated - parent key not found

Any help is greatly appreciated!

like image 935
trick5gee Avatar asked Feb 10 '26 20:02

trick5gee


2 Answers

First, you need to insert the root value.

> insert into TableTest values ('A1', null);
> insert into TableTest values ('A3', 'A1');
like image 60
Pablo Santa Cruz Avatar answered Feb 13 '26 08:02

Pablo Santa Cruz


There are cases, just like the one you posted, where circular references (which are absolutely fine by the way, no logical issue there) conflict with the normal way relational integrity constraints work. This is because relational integrity has some "directional" features (primary key comes first, then foreign key) even though dependencies can be circular, as you have seen.

There are several work-arounds. The easiest is to make the foreign key constraint deferred. That means that the constraint is checked only when you commit, not after each individual insert.

Another is to insert all values at the same time (in the same INSERT statement); for example:

insert into tabletest(ent, dep)
  select 'A1', 'A3' from dual union all
  select 'A3', 'A2' from dual union all
  select 'A2', 'A1' from dual
;

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!