Polymorphic Associations

Difficulty: Advanced

Question

What is a polymorphic association in database design, and what are its problems and alternatives?

Answer

A polymorphic association is when one table can belong to rows in several different parent tables through a single relationship, usually stored as a pair of columns like commentable_type and commentable_id. For example, a comments table can point at a posts row or a videos row. It is convenient and popular in ORMs like Rails and Laravel, but the database cannot enforce it with a real foreign key.

How the pattern is stored

The child table holds two columns instead of a normal foreign key:

  • commentable_type: the name of the parent table or model, such as 'Post' or 'Video'.
  • commentable_id: the primary key value in that parent table.

The ORM reads the type column and decides which table to query. Rails calls this belongs_to :commentable, polymorphic: true; Laravel uses morphTo; Django has GenericForeignKey in the contenttypes framework.

Why database purists dislike it

  • No referential integrity. A FOREIGN KEY must reference exactly one table, so nothing stops commentable_id = 999 pointing at a deleted or non-existent post. Orphans accumulate.
  • No cascading deletes. ON DELETE CASCADE cannot work, so the application must clean up children, and it often forgets.
  • Awkward joins. To list comments with their parent titles you need a LEFT JOIN per parent type plus a CASE, or several queries.
  • Type strings leak code. Renaming the Post class in code silently breaks every stored row unless you migrate the data.
  • Indexing needs a composite index on (commentable_type, commentable_id) to be efficient.

Alternatives that keep real foreign keys

ApproachHow it worksTrade-off
Exclusive arcNullable post_id and video_id columns plus a CHECK that exactly one is setReal FKs; add a column per new parent type
Separate join tablespost_comments, video_comments each linking to a shared comments tableClean FKs; more tables
Common supertypeA commentable parent table; posts and videos each have a commentable_id FK to itProper inheritance; extra insert per parent
Separate child tablespost_comments and video_comments with their own columnsSimplest integrity; duplicated structure

The exclusive arc is the most common upgrade path. In PostgreSQL, CHECK (num_nonnulls(post_id, video_id) = 1) enforces "exactly one parent" neatly.

When the polymorphic pattern is acceptable

It is a reasonable choice for low-stakes, append-heavy, cross-cutting data where orphans are harmless: activity feeds, audit logs, tags, likes, notifications. A product like a learning platform might attach "bookmarks" to courses, lessons and articles this way. For anything financial or where deletion must cascade correctly, prefer one of the FK-based designs.

Common mistakes

  • Indexing only commentable_id, so queries scan every type's rows.
  • Storing the type as free text without a CHECK constraint or enum, allowing typos like 'post' vs 'Post'.
  • Assuming the ORM will clean up children on delete without configuring dependent: :destroy or equivalent.
Polymorphic columns vs exclusive arc. The exclusive arc trades one extra column per parent type for real foreign keys.
Polymorphic (type + id)Exclusive arc
Columns on commentscommentable_type, commentable_idpost_id, video_id (nullable)
Foreign key enforcedNoYes, one FK per column
ON DELETE CASCADENot possibleWorks normally
New parent typeNo schema changeAdd a column and update the CHECK

Code examples

Classic polymorphic table (no FK possible)

CREATE TABLE comments (
  id               BIGSERIAL PRIMARY KEY,
  commentable_type TEXT   NOT NULL CHECK (commentable_type IN ('Post', 'Video')),
  commentable_id   BIGINT NOT NULL,
  body             TEXT   NOT NULL,
  created_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Composite index so lookups by parent are fast
CREATE INDEX comments_parent_idx ON comments (commentable_type, commentable_id);

The CHECK limits valid types, but nothing guarantees commentable_id exists in the matching table.

Exclusive arc with real foreign keys (PostgreSQL)

CREATE TABLE comments (
  id         BIGSERIAL PRIMARY KEY,
  post_id    BIGINT REFERENCES posts(id)  ON DELETE CASCADE,
  video_id   BIGINT REFERENCES videos(id) ON DELETE CASCADE,
  body       TEXT NOT NULL,
  -- exactly one parent must be set
  CONSTRAINT one_parent CHECK (num_nonnulls(post_id, video_id) = 1)
);
CREATE INDEX ON comments (post_id)  WHERE post_id  IS NOT NULL;
CREATE INDEX ON comments (video_id) WHERE video_id IS NOT NULL;

Each parent column is a genuine foreign key with cascading delete, and partial indexes keep the indexes small.

Key points

  • Polymorphic association = type column + id column pointing to one of several parent tables.
  • A foreign key can reference only one table, so the database cannot enforce polymorphic links.
  • Exclusive arc, join tables, or a common supertype table restore referential integrity.
  • Always index (type, id) together if you use the polymorphic pattern.
  • Acceptable for likes, tags, activity logs; risky for financial or cascading data.

Common follow-up questions

  • How would you clean up orphaned rows created by a polymorphic association?
  • How do you write a query that lists comments along with their parent titles?
  • How does table inheritance in PostgreSQL relate to this problem?
  • What happens to stored type values when you rename a model class?

Interview tips

  • Name the core problem directly: no foreign key, so no referential integrity or cascades.
  • Offer at least one alternative with a concrete constraint, such as the num_nonnulls CHECK.
  • Show balance: admit the pattern is fine for low-risk data rather than calling it always wrong.

Concepts covered

Polymorphic Association, Foreign Key, Exclusive Arc, Referential Integrity, ORM

More Database Design questions