
SaaS Unique Constraints: Define Business Identity Before Preventing Duplicate Records
Define tenant-scoped business identity, normalization, null handling, and conflict recovery before adding database uniqueness rules.
MVPs & SaaS Projects
Choose SaaS foreign-key rules by examining record lifecycles, tenant relationships, deletion consequences, migration evidence, and the behavior users should see.

LET’S BUILD SOMETHING USEFUL
Talk to ATARAXY DEVELOPERS (SMC-PRIVATE) LIMITED about your website, app, or custom software.
A SaaS deletion button can appear to work while leaving records that no longer belong anywhere. A project disappears, but its tasks remain in reports; a customer is removed, but invoices lose the context needed to explain them. Foreign keys help enforce relationships inside the database. Their value depends on choosing rules that match the product’s lifecycle instead of selecting a deletion action merely because it makes an error disappear.
Consider a hypothetical project-management service with projects, tasks, activity records, and customer organizations. Some task details have no purpose after a project is permanently removed. Other records may need to remain understandable independently. Before writing a migration, list the relationships and describe what should happen to each child record when its parent is archived, removed, or replaced. Those are product decisions that the database can then help enforce.
An ordinary column containing a project identifier does not by itself guarantee that the project exists. A foreign key defines a database-enforced relationship to a referenced key. The PostgreSQL constraints documentation explains these relationships, including composite keys and deletion actions. Use the constraint to express an invariant the product actually requires, then make application behavior consistent with that invariant.
Write the rule in plain language before choosing the columns. Every task might require an existing project, while an optional account manager assignment may legitimately be empty. In PostgreSQL, nullable foreign-key columns can allow rows without a matching reference; use the appropriate nullability rules when the relationship is mandatory. Test both an invalid identifier and an absent value so an apparently protected relationship does not retain an unintended escape route.
PostgreSQL supports actions such as cascading deletion, rejecting deletion, or setting referencing values to null or a default, subject to other constraints. The default NO ACTION and RESTRICT have different timing behavior when deferral is involved. Choose deliberately rather than treating their names as interchangeable. Keep the technical choice in the migration review alongside the business explanation for the resulting child records.
For the project example, permanently deleting temporary calculation rows might be appropriate when their project is removed. Deleting a completed invoice through the same cascade could violate the product’s required recordkeeping behavior. If a child must remain, preserve enough context for it to make sense and decide whether the parent may be removed at all. A null reference without an understandable display state can leave users with an equally confusing result.
Marking a project archived changes a field; it does not physically remove the row. A foreign key that checks the row’s existence will not automatically prevent new tasks from being attached to an archived project. If the product prohibits that action, enforce the lifecycle rule in the write path or another suitable database design. Do not assume a valid relationship means every business action involving it is currently allowed.
Define what restoration means before introducing a soft-delete flag. Can an archived project return with the same tasks and assignments? Can its old name be reused? Are scheduled jobs still permitted to act on it? Keep these decisions separate from the permanent deletion plan. The interface should explain whether a user is hiding a record, ending its active lifecycle, or requesting an irreversible removal process.
In a multi-tenant service, a task must often belong to a project in the same organization. A foreign key to a globally unique project identifier proves existence but may not express that tenant match. A suitable composite relationship can include the organization identifier where the referenced key design supports it. Review the exact schema rather than assuming that adding a tenant column elsewhere establishes the invariant.
Database relationship checks also do not replace authorization. A project can exist in the correct tenant while a particular user lacks permission to edit it. Check the actor’s allowed operation and the database’s structural requirements as separate responsibilities. Test cross-tenant identifiers through imports, background jobs, and API requests, including paths that bypass the normal project selector in the user interface.
Give users a meaningful explanation of the requested operation. For a project with dependent tasks, show the relevant counts and distinguish records that will be removed from records that prevent removal. Avoid presenting a preview as a guarantee if new children can be created before the final action. Recheck the applicable rules when the operation is committed and return a clear conflict outcome when conditions have changed.
Keep external effects in view. A database cascade does not automatically delete object-storage files, revoke external sharing links, or cancel a job in another service. Plan those effects with an explicit workflow and reconciliation strategy. Record which steps have completed so a retry resumes the required work instead of deleting unrelated resources or claiming that every external copy disappeared when only a database row was removed.
Inventory rows whose parent is missing, whose tenant differs, or whose required reference is empty. Group the exceptions by cause and decide how each will be repaired. Some may require restoring a legitimate parent; others may need a reviewed reassignment or removal. Do not automatically attach every orphan to a catch-all account simply to make the migration pass, because that hides the original data problem.
Plan validation and rollout against the size and activity of the real tables. Review database-specific migration behavior with the team responsible for operations, and test on representative data. Preserve a record of the exceptions found and the decisions applied. AI can help draft diagnostic queries or summarize exception groups, but reviewed queries and verified records should determine the actual repair, especially when tenant ownership is involved.
Build tests around meaningful behavior: creating a valid child, rejecting a missing parent, rejecting an invalid tenant relationship, and handling parent deletion with each approved outcome. Include multiple child levels so a cascade’s reach is visible. Verify that error responses guide the user toward a sensible next step rather than exposing raw database messages or suggesting repeated retries for a prohibited operation.
Also test concurrent activity and recovery. A deletion racing with task creation should resolve according to the defined rules, with neither operation reporting a false success. After a failed workflow, inspect both database records and external resources. Keep representative queries in the operational runbook so support staff can distinguish an intentional retained record from a genuine orphan without improvising a destructive cleanup.
Foreign keys are most effective when their rules follow the product’s record lifecycles. Decide which relationships are required, how tenant boundaries are expressed, and what each deletion action means for users. Separate archiving from physical removal and account for resources outside the database. Reconcile existing exceptions and test complete workflows so structural integrity remains understandable throughout the life of the SaaS product.
LET’S BUILD SOMETHING USEFUL
Talk to ATARAXY DEVELOPERS (SMC-PRIVATE) LIMITED about your website, app, or custom software.