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:
- 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.
- 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 toRESTRICTduring standard check, but may differ at runtime.
- 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 toRESTRICTduring 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.