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:
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 purposeError: CHECK constraint failed: (post_id IS NOT NULL) + (photo_id IS NOT NULL) = 1The 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.
-- 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