Skip to content
Advertisement

Violation of uniqueness in primary key when using inheritance

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:

The childs are:

When i use these INSERTs :

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 be UNIQUE or a PRIMARY KEY, this would not stop the capitals table from having rows with names duplicating rows in cities. And those duplicate rows would by default show up in queries from cities.

If you SELECT * FROM parent, PostgreSQL effectively executes:

You can look at the EXPLAIN output to verify that.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement