1 Missing Foreign Keys
The Mistake
Using integer columns to reference other tables without adding FOREIGN KEY constraints. The database happily accepts orphaned rows and invalid IDs.
⚠️ What goes wrong
- Orphaned rows pile up over time
- Application code must validate every reference
- Deleting a parent leaves dangling child records
- Impossible for the database to enforce referential integrity
The Fix
CREATE TABLE comments ( id SERIAL PRIMARY KEY, post_id INT NOT NULL REFERENCES posts(id) ON DELETE CASCADE, user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, body TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW() ); CREATE INDEX idx_comments_post ON comments(post_id); CREATE INDEX idx_comments_user ON comments(user_id);