Ira SQL ProIra SQL Pro

Table Inheritance

advancedpostgresql
2 min read

What is Table Inheritance?

PostgreSQL supports table inheritance where a child table inherits all columns and some constraints from a parent table. Querying the parent table includes rows from all children.

Syntax

CREATE TABLE people (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100)
);

CREATE TABLE students (
  grade CHAR(1),
  enrollment_date DATE
) INHERITS (people);

CREATE TABLE employees (
  department VARCHAR(50),
  hire_date DATE
) INHERITS (people);

When to Use

  • Modeling "is-a" relationships (a student is a person)
  • Partitioning data across related tables (now prefer declarative partitioning)
  • Sharing common columns across similar table types

Key Points

  1. Column Inheritance — Child tables automatically have all parent columns.
  2. Query ParentSELECT * FROM people includes rows from students and employees.
  3. ONLY KeywordSELECT * FROM ONLY people queries only the parent, excluding children.
  4. Constraints — CHECK constraints are inherited. UNIQUE and FK constraints are not.
  5. Modern Alternative — For partitioning, use declarative partitioning (PARTITION BY) instead.
  6. PostgreSQL Specific — Table inheritance is unique to PostgreSQL.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

Table Inheritance Challenge

Write a query that solve this task: create students and employees inheriting from people.

Expected result

students table has id, name, email (inherited) and grade (own) columns.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What is Table Inheritance?

Initializing database...Each run starts from fresh sample data.

More Examples

Query parent includes children

Select from the parent to see all people.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

Are UNIQUE constraints inherited?
No. UNIQUE and PRIMARY KEY constraints are not inherited. A child can have duplicates of the parent's values.
Should I use table inheritance for partitioning?
No. Since PostgreSQL 10, declarative partitioning (PARTITION BY RANGE/LIST/HASH) is the recommended approach.

Related Topics