Skip to content
Engineer
Menu
Design
English

Engineer / Glossary

Foreign key

a constraint that requires a matching referenced key

What it is

A foreign key is a database constraint that requires values in one table to refer to an eligible key in another table, or sometimes in the same table. An order can carry a customer identifier whose value must exist in the customer table. Unless an applicable null rule permits an absent reference, the database rejects a row if the referenced key does not exist. The referenced key may be a primary key or another eligible unique key. A foreign key can cover one column or several, and many referencing rows can point at the same target.

A tenant-specific catalogue provides a useful multicolumn example. Suppose product numbers are only unique inside a tenant. An order line should identify the product with both the tenant identifier and the product number. A foreign key built from both columns can require the pair to exist in the catalogue. The database then checks the relationship that the application actually needs. A reference to a globally unique product ID would guarantee existence, but additional rules would still be needed to ensure that both rows belong to the same tenant if the tenant is stored separately.

The constraint also affects changes to the referenced row. A database can reject an attempted deletion, propagate it to the referencing rows, or apply a defined alternative such as setting a nullable reference to null. Policy and terminology differ among databases. PostgreSQL supports deferrable checks for eligible constraints, which can let transactions put related rows into place in several steps before the relationship is checked. Choose an action based on the lifecycle of the data, then confirm the database’s exact timing and behaviour.

Why it matters

An application can check a customer before creating an order. A second writer may delete that customer between the lookup and the order insert. Database-level referential integrity lets the service express a rule that all writers must follow and lets the engine coordinate concurrent changes that affect it. Imports, background jobs and maintenance scripts receive the same constraint as the primary application. They can still arrange their work differently within the transactions the engine allows.

Downstream readers also benefit. A report that joins a required reference can be written with a more reliable expectation of what exists. When references are optional, the report should still account for the missing relation. The constraint guarantees the declared relationship. It leaves questions such as whether a customer is active, whether an invoice should remain visible after account closure and whether a user has access to a row to other application and database rules.

Foreign keys change the work done on writes. An insert must find a referenced row and a change to a target row may need to find its references. PostgreSQL requires an eligible unique key on the referenced side and does not automatically index the referencing columns. An index on the referencing side can support checks for deletion and update as well as ordinary joins. Evaluate it against the workload and keep the costs of additional indexes in view.

What it looks like in practice

Create a representative test catalogue with two tenants and product numbers that repeat across them. Insert valid order lines for each tenant. Try a product number that exists for a different tenant but has no row for the order’s tenant. Confirm that the database rejects it and that the application presents a result the operator can act on. Then try deleting a referenced catalogue entry while an old order line still exists and check the effect the retention policy requires. A rejection, preserved association or explicit null each tells the business something different about what remains available.

If the constraint is being added to populated tables, check the existing pairs first. List orphaned rows and determine whether they should be repaired, archived or investigated. PostgreSQL can install certain constraints with NOT VALID to enforce new writes while leaving existing rows to a later validation step. That period needs an owner and an explicit completion condition. Try the full migration, validation and application change on an example with existing data and measure lock waits before rolling it out.

Our maritime database modelling case study explains why relationships between professionals, companies, ships and jobs matter and how normalised schemas organise them. The catalogue example illustrates how to enforce one specific relationship. The case gives a reason to make key semantics and ownership explicit when a model contains many related entity types.

Where it goes wrong

A single-column key on a nearby field can express the wrong promise. Check that every part of the relationship is represented, especially when IDs are scoped to an account, site or environment. A nullable foreign key also has different semantics from a required association. Add a suitable null constraint if the relationship must be present, then test partial nulls on multicolumn references according to the selected match rule.

Cascading deletes can remove data still needed by business or legal processes. Model ownership before choosing a cascade. A short-lived detail row may belong completely to its parent, while a retained invoice may need to survive account closure. Test the graph with representative child counts and inspect the effects that will appear to downstream readers. A cascade that looks harmless in a small test can also take substantial time under production volumes.

Check that the target engine enforces the constraints in all relevant connection modes. SQLite generally requires enabling foreign key enforcement for each connection unless the library build changes the default. Verify the setting through the same connection path the service uses and deliberately try an invalid write. When an import uses temporary enforcement exceptions, run explicit validation and record the result before anybody relies on the imported references.

Further reading

Contact

Still working out what you need?

Tell us what is going wrong, or what you are trying to build. We will tell you what it would take, roughly what it would cost, and whether we are the right people for it.

From 1,400 DKK an hour, excluding VAT — and less per hour on a longer booking.

welcome@engineer.company +45 50 10 61 84 Copenhagen, Denmark