Foreign key (source code)

= Foreign key
{wiki}

A <foreign key> is a <database integrity constraint> requiring designated <database attributes> to match a referenced identifier in a <database relation>. The referenced <database relation> may be the same one: a self-reference can represent each employee's manager. The identifier being referenced must have the required uniqueness, but the referencing <database attributes> need not be unique; several employees can have the same manager.<Constraints in the PostgreSQL documentation>[version 18, section 5.5.5, foreign keys and self-referential tree example]{ref}

For a simple example, let `Instrument(id)` contain identifiers $4,9$. A <measurement> carrying `instrument_id=4` has a matching <scientific instrument>; one carrying `instrument_id=7` violates the <foreign key>. Deleting <scientific instrument> four while <measurements> still refer to it requires a stated policy: reject the deletion, cascade a suitable deletion, or apply another permitted referential action.<Constraints in the PostgreSQL documentation>[version 18, section 5.5.5, referential actions]{ref}

<SQL NULL> and compound <foreign keys> require an explicit matching policy. A nullable simple reference can represent no parent, whereas `NOT NULL` can require a reference. A <foreign key> enforces reference existence; it does not by itself prove that a self-referencing structure has no <directed cycles>.