The invoice is still there. The customer is not. An invoice refers to customer 417, whose record was removed, and a later report displays a blank name. The data may have been valid when each application screen was tested. The problem is the relationship between two tables, and there was no shared rule protecting it.
A foreign key is a database constraint that requires a referencing value to match an eligible referenced key, subject to null and constraint rules. In PostgreSQL it can also specify what happens when the referenced row is updated or deleted. The PostgreSQL constraints guide explains the supported actions. A foreign key protects a specific relationship; it does not establish that an invoice amount is correct, that the customer is active, or that a person was authorized to create it.
Start with the orphan, not the schema diagram
Take two tables: customers, keyed by customer ID, and invoices, each carrying an invoice ID and a customer ID. A foreign key from invoices.customer_id to customers.customer_id prevents an invoice from pointing at a customer key that does not exist when the constraint is checked. If the relationship is mandatory, a separate not-null rule may also be needed; a foreign key alone does not necessarily prohibit a null value.
This distinction matters when a report shows missing customer names. A null customer ID, an invalid non-null ID, and a valid ID whose customer has an empty name are three different issues. The constraint can address the invalid reference. It cannot make an incomplete customer record meaningful or decide whether an invoice should have been issued.
Composite keys add another question: which columns together define the identity? A system serving several organizations might identify a customer by both tenant ID and customer number. If only the customer number is referenced, a relationship can point across the wrong tenant even though a number exists somewhere. The referenced key, referencing columns, and application access rules must reflect the actual identity boundary. A constraint is not a substitute for authorization.
Deletion is a business decision encoded as a rule
When someone deletes a referenced customer, PostgreSQL can apply different actions. The default NO ACTION checks that the relationship remains valid when the constraint is checked. RESTRICT prevents the action under its documented timing. CASCADE propagates the deletion to referencing rows. SET NULL and SET DEFAULT alter referencing values, subject to the resulting values satisfying the relevant constraints.
These are not interchangeable convenience settings. Cascading from an order to a temporary order-line table may fit a carefully designed process. Cascading from a customer to invoices can erase records the business needs for accounting, disputes, or retention. Setting a reference to null preserves the invoice row but may remove an association needed to explain it. The correct action depends on the record’s purpose and the surrounding requirements.
Say the fictional customer has three invoices totaling $1,800. A cascade would remove three rows if those relationships are configured to cascade; it would not merely remove a label from a report. A restrictive action would reject the deletion while references remain. An application might instead mark the customer inactive, but that is a separate design and must still address retention and privacy obligations. No generic article can select the right policy for every business.
The database checks timing too
Some constraints can be declared deferrable, allowing their checks to occur later in a transaction under the specified settings. That can help when a valid sequence temporarily looks inconsistent while several related rows are rearranged. It is not a license to leave the committed database inconsistent. PostgreSQL’s SET CONSTRAINTS documentation explains when deferrable checks can be moved and when an immediate check occurs.
Consider transferring a set of related records under a controlled transaction. If the chosen constraint is deferred, the intermediate order of statements may be less restrictive, but the final transaction still has to satisfy the rule. If the transaction fails, the application needs to handle the error and decide what to retry or report. Moving a check later can move the error later too, making it less obvious which earlier action caused it.
Do not confuse a foreign-key check with isolation between concurrent operations. A relationship may remain valid while two users still encounter a lost update or an unexpected view of other data. The transaction-isolation guide covers that separate problem. The database may enforce several kinds of rules at once; each answers a different question.
Why a correct rule can surprise a busy system
The referenced key must meet the database’s eligibility rules. In PostgreSQL, the referenced columns generally correspond to a primary key, unique constraint, or suitable non-partial unique index. The database needs a reliable way to decide which row the relationship names. A label that merely looks unique to the application is not a substitute for a defined key.
The other side of the relationship deserves attention too. PostgreSQL does not automatically create an index on the referencing columns just because a foreign key is declared. When a referenced row is deleted or its key changes, the database may need to find referencing rows. On a large child table, an appropriate index can matter. Whether to create it, and in what column order, depends on the workload and other indexes already present.
Consider one customer has five invoices in a table containing ten million rows. Without an appropriate access path, checking the relationship during a deletion can involve far more work than the five matching invoices suggest. That is an illustration of why the lookup matters, not a prediction of a particular plan. Use representative queries and the database’s plan tools; a redundant index carries its own write and storage cost. Our index guide explains that tradeoff.
Adding the rule to an existing table
A new constraint must be considered alongside the data already stored. Before changing a production schema, identify orphaned references, nulls, duplicate candidate keys, and the business meaning of each exception. An invalid invoice might belong to a missing customer, a merged account, an incorrect import, or a record that should no longer be active. Replacing every missing ID with a convenient placeholder can hide the issue while making reports less trustworthy.
PostgreSQL offers options for adding certain constraints without immediately validating all existing rows, followed by a separate validation step. The exact behavior, locking implications, permissions, and supported constraint types belong to the installed version’s ALTER TABLE documentation. Plan and test the migration with a representative dataset and a recovery path. A completed schema change is not proof that every historical exception has been reconciled.
Define who decides what a suspicious record means. The developer can locate an orphan; an accounting or operations owner may need to identify the real customer and retain an audit trail. Test the application’s behavior when the database rejects a bad write. A raw constraint error at checkout is technically honest but not a useful customer experience, while a swallowed error can leave the user believing an invoice was saved when it was not.
Give the reconciliation an owner and a repeatable rule: repair a verified reference, preserve a legitimate exception in an intentional model, or investigate the record. Check for writes arriving during the migration as well. A one-time report is only a snapshot, so coordinate the constraint rollout with the applications that create and change these rows. The database can then enforce the chosen rule for future changes; it cannot decide what the old records were supposed to mean.
When the parent is renumbered
Deletes get the dramatic examples, but a change to a referenced key can be just as disruptive. Imagine that the business wants to replace customer number 417 with 9417. If invoice rows store that number as their reference, a key update can leave the same question as a deletion: what happens to the invoices that still name 417? The constraint's update action determines whether the operation is rejected or the referencing values are changed in a permitted way.
PostgreSQL supports actions for updates as well as deletes, but choosing ON UPDATE CASCADE is not a substitute for checking other consumers. An export, an external accounting system, or a document already sent to a customer may retain the old number. The database can update its own configured relationships; it cannot update a paper invoice sitting in someone's inbox or an unrelated system that never joined the transaction.
One alternative is a stable internal identifier with a separate customer-facing number that can change. That makes the relationship less dependent on a label used in the business process, though it introduces a mapping that must itself be maintained. If the external number must be unique, define and test that separate rule too. Stable keys make a class of update easier to reason about; they do not eliminate the need to reconcile systems or explain changed identifiers to their owners.
Before the delete button becomes a policy
Which row is being referenced, and what makes its key unique? Is the reference required, or can it be null? What should happen if the parent changes or is deleted? How will the system find and explain affected child rows at the scale it actually operates?
Answer those questions with the people who own the records, then test the choices against ordinary work and failure cases. A foreign key is valuable precisely because it turns a relationship from an assumption in one application into a rule shared by every writer. Its usefulness depends on choosing the relationship—and the consequences of changing it—deliberately.
Explore Infinite Upside
For Vijay Sheth’s personal accounts, read Infinite Upside: Building Wealth With Room to Live, published by Sheth Capital, Inc.
Explore a related guide
What Does Database Transaction Isolation Change?