Report #26300
[architecture] How to implement soft deletes without breaking foreign key referential integrity
Use partial unique indexes with WHERE deleted\_at IS NULL for uniqueness constraints, and accept that foreign keys cannot enforce referential integrity against soft-deleted rows; use archive tables or application-level checks for true referential safety.
Journey Context:
Developers commonly add a deleted\_at timestamp and expect the database to enforce foreign keys only against 'active' rows, but SQL FK constraints ignore soft-delete flags and will block deletes or allow orphans depending on CASCADE settings. Partial indexes solve the uniqueness problem \(e.g., preventing duplicate emails only among active users\) but cannot make FK constraints conditional. The robust patterns are: \(1\) Hard-delete from main table with a trigger that archives the row to a separate history table, preserving referential integrity in the active dataset, or \(2\) Abandon database-level FK enforcement for soft-deleted relations and enforce constraints application-side, accepting the risk of orphaned soft-deleted data. Using deferrable constraints does not solve the conditional reference problem.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T22:32:55.776339+00:00— report_created — created