0

If I have a base table and 2 or more tables that inherit from it, child1 and child2, I can insert a record into a child table and it shows up in base as you would expect. However what I want to know is, is it possible to have a record that is present in both child1 and child2?

As an example say base is vehicle, child1 is boat and child2 is car, And I want to insert an amphibious car (effectively both a boat and a car).

I know I could do this the normal way, by having relationships but in theory it could be neat if it's possible to do as described.

1
  1. I advise never using INHERITS, even in simple single-inheritance cases
  2. Not sure why you think this would not be possible.

I would certainly never do this butttt.... you have Multiple Inheritance too if you're really masochistic. From the docs on Inheritance

A table can inherit from more than one parent table, in which case it has the union of the columns defined by the parent tables. Any columns declared in the child table's definition are added to these. If the same column name appears in multiple parent tables, or in both a parent table and the child's definition, then these columns are "merged" so that there is only one such column in the child table. To be merged, columns must have the same data types, else an error is raised. The merged column will have copies of all the check constraints coming from any one of the column definitions it came from, and will be marked not-null if any of them are.

Example

CREATE TABLE vehicle ( name text );
CREATE TABLE boat () INHERITS (vehicle);
CREATE TABLE car () INHERITS (vehicle);

--ewww,
CREATE TABLE boatcar () INHERITS (boat,car);
NOTICE:  merging multiple inherited definitions of column "name"

INSERT INTO boatcar (name) VALUES ('amphibious car');

TABLE boatcar ;
      name      
----------------
 amphibious car
(1 row)

TABLE boat;
      name      
----------------
 amphibious car
(1 row)

TABLE car;
      name      
----------------
 amphibious car
(1 row)

TABLE vehicle ;
      name      
----------------
 amphibious car
(1 row)
  • @TypoCubeᵀᴹ updated. – Evan Carroll Jan 3 '17 at 23:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.