← Back to SQL, page 24

sql-0461 · Hard senior

Comments can belong to posts, photos or videos. How should the comments table reference its parent?

A 'polymorphic' design with parent_type and parent_id columns is common in ORMs, but the database cannot enforce a foreign key on it. Safer options are separate nullable foreign key columns (post_id, photo_id, video_id) with a CHECK that exactly one is set, or a shared parent table (commentables) that posts, photos and videos each reference.

Full answer

Option 1, polymorphic pair (no referential integrity):

text
comments(id, parent_type TEXT, parent_id BIGINT, body)

Deleting a post leaves orphaned comments unless application code cleans up.

Option 2, exclusive foreign keys:

text
comments(id, post_id REFERENCES posts, photo_id REFERENCES photos, video_id REFERENCES videos, body,
         CHECK ((post_id IS NOT NULL)::int + (photo_id IS NOT NULL)::int + (video_id IS NOT NULL)::int = 1))

Real foreign keys and cascades work; adding a new parent type needs a new column.

Option 3, supertype table:

text
commentables(id PK, kind)
posts(id PK REFERENCES commentables(id), ...)
comments(id, commentable_id REFERENCES commentables(id), body)

One foreign key, any number of parent kinds, at the cost of creating a commentables row with each parent.

Option 4, separate tables per parent (post_comments, photo_comments) is simple but duplicates logic.

The CHECK syntax shown casts booleans as in PostgreSQL; SQLite accepts the comparison results directly as 0 and 1. Not run here.

Key points

  • Polymorphic pairs lack foreign keys
  • Exclusive FKs with a CHECK enforce integrity
  • A supertype table generalises
  • Separate tables duplicate logic
  • Choose by how often parent types are added

Common mistakes

  • Relying on application code for integrity
  • Allowing several parent columns set at once

Follow-ups

  • How would you count comments per parent across types?
  • How do ORMs map each option?

Tips

  • Compare integrity across the options