Working with Table Inheritance

1. Creating Parent Table

CREATE TABLE vehicle (id serial PRIMARY KEY, make text, model text);

2. Creating Child Table

CREATE TABLE car (doors int) INHERITS (vehicle);
CREATE TABLE truck (capacity_kg int) INHERITS (vehicle);

3. Querying All Tables Including Children

SELECT * FROM vehicle;     -- includes car & truck rows

4. Querying Parent Only

SELECT * FROM ONLY vehicle;

5. Understanding Constraint Inheritance

ConstraintInherited?
NOT NULLYes
CHECKYes (marked inherited)
PRIMARY KEYNo (child needs own)
UNIQUENo
FOREIGN KEYNo (parent-side FKs don't see children)

6. Understanding Unique Constraint Limitations

Warning: A UNIQUE on parent is not enforced across children. Same value may exist in car and truck.

7. Overriding Parent Columns

CREATE TABLE car (
   model text NOT NULL,           -- tightens parent
   doors int
) INHERITS (vehicle);

8. Altering Parent Table

ALTER TABLE vehicle ADD COLUMN year int;
-- propagates to all descendants; use ONLY to skip
ALTER TABLE ONLY vehicle ADD COLUMN tag text;

9. Understanding Inheritance vs Partitioning

FeatureInheritanceDeclarative Partitioning
Routing INSERTManual / triggerAutomatic
Global indexes / FKsNoPartitioned index (PG 11+)
Use todayLegacy / mix-in columnsAll new partition designs

10. Dropping Child Table

DROP TABLE car;
-- or detach: ALTER TABLE car NO INHERIT vehicle;