I’m using inheritance in PostgreSQL but there is a big problem while using it. I have a Parent table and 2 Child Tables and I don’tknow how to insert a data in these tables. The uniqueness of Parent primary key become violated when I insert some data into child tables.
The parent table is:
CREATE TABLE Parent ( pid int not null, pAttr1 int not null, primary key (pid) )
The childs are:
CREATE TABLE child1 ( ChAttr1 int not null ) INHERITS (Parent) CREATE TABLE child2( ChAttr2 int not null ) INHERITS (Parent)
When i use these INSERTs :
INSERT into Parent values (1,10) INSERT into Child1 values (1,20,30) --1 for pk, 20 for pAttr1 & 30 for ChAttr1 INSERT into Child2 values (1,50,60)
Then there are 3 entities with primary key of 1 in Parent table!!!
Advertisement
Answer
That is documented:
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:
- If we declared
cities.name
to beUNIQUE
or aPRIMARY KEY
, this would not stop thecapitals
table from having rows with names duplicating rows incities
. And those duplicate rows would by default show up in queries fromcities
.
If you SELECT * FROM parent
, PostgreSQL effectively executes:
SELECT pid, pattr1 FROM parent UNION ALL SELECT pid, pattr1 FROM child1 UNION ALL SELECT pid, pattr1 FROM child2;
You can look at the EXPLAIN
output to verify that.