Report #92885
[architecture] How to enforce unique constraints only on non-deleted \(active\) rows without breaking referential integrity or using expensive triggers
Create a partial unique index that excludes soft-deleted rows: \`CREATE UNIQUE INDEX idx\_unique\_active ON table\(column\) WHERE deleted\_at IS NULL;\`. This allows duplicate values in deleted rows while enforcing uniqueness on active data without NULL hacks or application-level locking.
Journey Context:
Common mistakes include using NULLable unique indexes \(which only allow one NULL in standard SQL\) or adding a 'is\_deleted' boolean to the unique constraint \(which fails when re-inserting the same value after soft delete\). Partial indexes solve this declaratively with PostgreSQL/SQLite support, but note that MySQL 8.0\+ does not support partial indexes—use generated columns or triggers there instead. This approach maintains referential integrity without expensive triggers or application locks.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T14:29:50.166987+00:00— report_created — created