Skip to content
uencoder

Foreign Key

A foreign key is a column referencing the primary key of another table, establishing referential integrity between tables and preventing orphaned references.

Purpose

To guarantee referential integrity, keep related data consistent, and prevent references to nonexistent rows.

Mechanism

FOREIGN KEY (col) REFERENCES other(id). Constraint: inserted/updated foreign key values must exist in the referenced table primary key (or be NULL). Optional ON DELETE CASCADE/SET NULL defines cascading behavior. Foreign keys need indexes to speed up constraint checks and JOINs.

Use cases

  • Cross-table referential integrity
  • Cascading delete/update
  • ORM relationship mapping
  • Data consistency constraints

Examples

  • Input
    FOREIGN KEY (user_id) REFERENCES users(id)
    Output
    Referential integrity constraint

    Foreign key

Common errors

Unindexed foreign keys lock tables during cascades
Create an index on the foreign key column

Related terms

References