{"canonical_url":"https://engineer.company/glossary/foreign-key/","content_markdown":"# Foreign key\n\n## What it is\n\nA foreign key is a database constraint that requires values in one table to\nrefer to an eligible key in another table, or sometimes in the same table. An\norder can carry a customer identifier whose value must exist in the customer\ntable. Unless an applicable null rule permits an absent reference, the database\nrejects a row if the referenced key does not exist. The referenced key may be a\nprimary key or another eligible unique key. A foreign key can cover one column\nor several, and many referencing rows can point at the same target.\n\nA tenant-specific catalogue provides a useful multicolumn example. Suppose\nproduct numbers are only unique inside a tenant. An order line should identify\nthe product with both the tenant identifier and the product number. A foreign\nkey built from both columns can require the pair to exist in the catalogue. The\ndatabase then checks the relationship that the application actually needs. A\nreference to a globally unique product ID would guarantee existence, but\nadditional rules would still be needed to ensure that both rows belong to the\nsame tenant if the tenant is stored separately.\n\nThe constraint also affects changes to the referenced row. A database can reject\nan attempted deletion, propagate it to the referencing rows, or apply a defined\nalternative such as setting a nullable reference to null. Policy and terminology\ndiffer among databases. PostgreSQL supports deferrable checks for eligible\nconstraints, which can let transactions put related rows into place in several\nsteps before the relationship is checked. Choose an action based on the\nlifecycle of the data, then confirm the database's exact timing and behaviour.\n\n## Why it matters\n\nAn application can check a customer before creating an order. A second writer\nmay delete that customer between the lookup and the order insert. Database-level\nreferential integrity lets the service express a rule that all writers must\nfollow and lets the engine coordinate concurrent changes that affect it.\nImports, background jobs and maintenance scripts receive the same constraint as\nthe primary application. They can still arrange their work differently within\nthe transactions the engine allows.\n\nDownstream readers also benefit. A report that joins a required reference can be\nwritten with a more reliable expectation of what exists. When references are\noptional, the report should still account for the missing relation. The\nconstraint guarantees the declared relationship. It leaves questions such as\nwhether a customer is active, whether an invoice should remain visible after\naccount closure and whether a user has access to a row to other application and\ndatabase rules.\n\nForeign keys change the work done on writes. An insert must find a referenced\nrow and a change to a target row may need to find its references. PostgreSQL\nrequires an eligible unique key on the referenced side and does not\nautomatically index the referencing columns. An index on the referencing side\ncan support checks for deletion and update as well as ordinary joins. Evaluate\nit against the workload and keep the costs of additional indexes in view.\n\n## What it looks like in practice\n\nCreate a representative test catalogue with two tenants and product numbers that\nrepeat across them. Insert valid order lines for each tenant. Try a product\nnumber that exists for a different tenant but has no row for the order's tenant.\nConfirm that the database rejects it and that the application presents a result\nthe operator can act on. Then try deleting a referenced catalogue entry while an\nold order line still exists and check the effect the retention policy requires.\nA rejection, preserved association or explicit null each tells the business\nsomething different about what remains available.\n\nIf the constraint is being added to populated tables, check the existing pairs\nfirst. List orphaned rows and determine whether they should be repaired,\narchived or investigated. PostgreSQL can install certain constraints with NOT\nVALID to enforce new writes while leaving existing rows to a later validation\nstep. That period needs an owner and an explicit completion condition. Try the\nfull migration, validation and application change on an example with existing\ndata and measure lock waits before rolling it out.\n\nOur\n[maritime database modelling case study](/portfolio/modeled-348-tables-across-34-postgres-schemas/)\nexplains why relationships between professionals, companies, ships and jobs\nmatter and how normalised schemas organise them. The catalogue example\nillustrates how to enforce one specific relationship. The case gives a reason to\nmake key semantics and ownership explicit when a model contains many related\nentity types.\n\n## Where it goes wrong\n\nA single-column key on a nearby field can express the wrong promise. Check that\nevery part of the relationship is represented, especially when IDs are scoped to\nan account, site or environment. A nullable foreign key also has different\nsemantics from a required association. Add a suitable null constraint if the\nrelationship must be present, then test partial nulls on multicolumn references\naccording to the selected match rule.\n\nCascading deletes can remove data still needed by business or legal processes.\nModel ownership before choosing a cascade. A short-lived detail row may belong\ncompletely to its parent, while a retained invoice may need to survive account\nclosure. Test the graph with representative child counts and inspect the effects\nthat will appear to downstream readers. A cascade that looks harmless in a small\ntest can also take substantial time under production volumes.\n\nCheck that the target engine enforces the constraints in all relevant connection\nmodes. SQLite generally requires enabling foreign key enforcement for each\nconnection unless the library build changes the default. Verify the setting\nthrough the same connection path the service uses and deliberately try an\ninvalid write. When an import uses temporary enforcement exceptions, run\nexplicit validation and record the result before anybody relies on the imported\nreferences.\n\n## Further reading\n\n- [PostgreSQL constraints](https://www.postgresql.org/docs/18/ddl-constraints.html)\n  covers referenced keys, nulls and referential actions.\n- [PostgreSQL ALTER TABLE](https://www.postgresql.org/docs/18/sql-altertable.html)\n  explains how to validate a constraint separately on an existing table.\n- [SQLite foreign key support](https://sqlite.org/foreignkeys.html) documents\n  connection settings, matching rules and checks.\n\n\u003chttps://engineer.company/glossary/foreign-key/\u003e\n","date_modified":"2026-11-24T21:48:58Z","description":"How a foreign key protects a relationship and what to verify before adding one to existing data.","formats":{"gemtext":"https://engineer.company/glossary/foreign-key/index.gmi","gopher":"https://engineer.company/glossary/foreign-key/gophermap","html":"https://engineer.company/glossary/foreign-key/","json":"https://engineer.company/glossary/foreign-key/index.json","markdown":"https://engineer.company/glossary/foreign-key/index.md","pdf":"https://engineer.company/glossary/foreign-key/index.pdf"},"kind":"page","language":"en","title":"What is a foreign key?","url":"https://engineer.company/glossary/foreign-key/","version":1}