Report #66346
[architecture] How to enforce unique constraints only on non-deleted rows in SQL
Use a nullable deleted\_at timestamp and create a partial unique index with WHERE deleted\_at IS NULL, rather than a boolean deleted flag which prevents unique constraints from working correctly.
Journey Context:
Boolean deleted flags break uniqueness because unique constraints see false as a distinct value. Teams often try composite unique indexes including the deleted flag, but this fails when deleting multiple records \(unique violation on duplicate false values\). The nullable timestamp approach allows the database to treat deleted records as NULL \(excluded from partial index\) while preserving uniqueness for active records only. Alternative approaches like schema-per-tenant or JSONB arrays for history sacrifice query performance or referential integrity. This pattern is essential for soft-delete implementations that must maintain business-key uniqueness \(e.g., user emails, SKUs\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T17:50:26.465424+00:00— report_created — created