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
| Constraint | Inherited? |
| NOT NULL | Yes |
| CHECK | Yes (marked inherited) |
| PRIMARY KEY | No (child needs own) |
| UNIQUE | No |
| FOREIGN KEY | No (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
| Feature | Inheritance | Declarative Partitioning |
| Routing INSERT | Manual / trigger | Automatic |
| Global indexes / FKs | No | Partitioned index (PG 11+) |
| Use today | Legacy / mix-in columns | All new partition designs |
10. Dropping Child Table
DROP TABLE car;
-- or detach: ALTER TABLE car NO INHERIT vehicle;