0

I'm working on a project for which I want to use inheritance (see code below)

When I try to insert something into Profile there is an error.

ERROR:  insert or update on table "profile" violates foreign key 
constraint "profile_id_fkey"
DETAIL:  Key (id)=(21) is not present in table "test".

I'm using PSequel to inspect the database and the values are visible in the parent. However, I am still able to insert a duplicate primary key in the parent. The insert then works.

CREATE TABLE Test ( 
ID INTEGER NOT NULL,
PRIMARY KEY (ID)
);

CREATE TABLE Testchild (
PRIMARY KEY (ID) 
) INHERITS (Test)
;


CREATE TABLE Profile (
ProfileID INTEGER NOT NULL, 
ID INT NOT NULL, 
PRIMARY KEY (ProfileID)
);

ALTER TABLE Profile
ADD FOREIGN KEY (ID) REFERENCES Test(ID);

INSERT INTO Testchild VALUES (21);

INSERT INTO Profile VALUES (1,21);
3
  • Your FK relationship is with Test table, not with TestChild. Try swapping in the Test table in the first insert and it will work Commented Oct 23, 2017 at 14:54
  • Thanks for you help! The problem is, I'm inheriting a couple of times from test. Do I have to have a FK relationship with all of the childen? Commented Oct 23, 2017 at 15:04
  • the relationship will be defined from one table - Profile with one table - Test. The child tables won't inherit it. Commented Oct 23, 2017 at 15:08

1 Answer 1

1

From PostgreSQL documentation:

A serious limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint. Thus, in the terms of the above example:

https://www.postgresql.org/docs/9.1/static/ddl-inherit.html

So you have to declare explicitly any FK, they wont inherit

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

Comments

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.