Sobes.tech
Junior

How does a foreign key affect data integrity in a database?

sobes.tech AI

Answer from AI

A foreign key enforces referential integrity of data, ensuring that the values in a column of one table (child table) correspond to the values in a column of another table (parent table).

Impact on data integrity:

  1. Prevents adding records to the child table with a non-existent value in the corresponding parent table column. Attempting to insert a row referencing a non-existent parent record will cause an error.
  2. Restricts deletion of records from the parent table that are referenced by records in the child table. The behavior upon deletion depends on the configured action (ON DELETE):
    • RESTRICT (default): Deletion is prohibited.
    • CASCADE: Deletes dependent records in the child table.
    • SET NULL: Sets the value to NULL in the corresponding child table column (if NULL is allowed).
    • NO ACTION: Similar to RESTRICT during standard check, but may differ at runtime.
  3. Restricts updating records in the parent table. The behavior upon update also depends on the configured action (ON UPDATE):
    • RESTRICT (default): Updating is prohibited.
    • CASCADE: Updates the corresponding value in dependent child records.
    • SET NULL: Sets the value to NULL in the corresponding child table column (if NULL is allowed).
    • NO ACTION: Similar to RESTRICT during standard check, but may differ at runtime.

A foreign key helps prevent the appearance of "orphaned" records and ensures that relationships between tables remain correct.

How does a foreign key affect data integrity in a… - sobes.tech