← Back to SQL, page 11

sql-0206 · Hard senior

How would you model an entity that can belong to one of several parent types, such as comments on either posts or photos?

A polymorphic column pair (parent_type, parent_id) is easy but cannot have a foreign key, so orphans are possible. Better options are separate nullable foreign keys with a CHECK that exactly one is set, separate comment tables per parent, or a shared supertype table that both posts and photos reference.

Full answer

Option A, polymorphic pair: comments(parent_type, parent_id). Simple and common in ORMs, but no foreign key can point to two tables, so deleting a photo leaves comments pointing at nothing.

Option B, exclusive foreign keys:

sql
PRAGMA foreign_keys = ON;
CREATE TABLE posts (id INTEGER PRIMARY KEY);
CREATE TABLE photos (id INTEGER PRIMARY KEY);
CREATE TABLE comments (
  id       INTEGER PRIMARY KEY,
  post_id  INTEGER REFERENCES posts(id),
  photo_id INTEGER REFERENCES photos(id),
  body     TEXT,
  CHECK ((post_id IS NOT NULL) + (photo_id IS NOT NULL) = 1)
);
INSERT INTO posts VALUES (1);
INSERT INTO photos VALUES (1);
INSERT INTO comments VALUES (1, 1, NULL, 'ok');
INSERT INTO comments VALUES (2, 1, 1, 'both parents');
-- error on purpose
text
Error: CHECK constraint failed: (post_id IS NOT NULL) + (photo_id IS NOT NULL) = 1

The CHECK requires exactly one parent. Each column has a real foreign key, so the database protects integrity. Adding a third parent type means adding a column.

Option C, separate tables (post_comments, photo_comments) keeps each simple but duplicates logic.

Option D, a supertype: a commentable(id) table that posts and photos each reference one-to-one, and comments reference commentable. It scales to many types with full integrity, at the cost of an extra join.

Choose B for a few stable parent types, D for many.

sql
-- error on purpose
PRAGMA foreign_keys = ON;
CREATE TABLE posts (id INTEGER PRIMARY KEY);
CREATE TABLE photos (id INTEGER PRIMARY KEY);
CREATE TABLE comments (
  id       INTEGER PRIMARY KEY,
  post_id  INTEGER REFERENCES posts(id),
  photo_id INTEGER REFERENCES photos(id),
  body     TEXT,
  CHECK ((post_id IS NOT NULL) + (photo_id IS NOT NULL) = 1)
);
INSERT INTO posts VALUES (1);
INSERT INTO photos VALUES (1);
INSERT INTO comments VALUES (1, 1, NULL, 'ok');
INSERT INTO comments VALUES (2, 1, 1, 'both parents');

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • (type, id) pairs cannot have foreign keys
  • Exclusive nullable foreign keys plus a CHECK keep integrity
  • A supertype table scales to many parent types
  • Pick by number and stability of parent types

Common mistakes

  • Using polymorphic pairs and never cleaning orphans
  • Forgetting the exactly-one CHECK with nullable foreign keys

Follow-ups

  • How would you query all comments with their parent titles?
  • How do ORMs usually implement polymorphic relations?

Tips

  • Name the integrity trade-off of each option