A foreign key is a fundamental concept in relational databases used to maintain data integrity and establish a relationship between two tables. It is a field (or a combination of fields) in one table that uniquely identifies a row of another table or the same table. The key's primary purpose is to ensure that the data between the two tables remains consistent. In a relational model, a foreign key in the referencing table refers to a primary key in the referenced table. This creates a link between the two tables, ensuring that the values in the referencing table correspond to valid entries in the referenced table.
https://en.wikipedia.org/wiki/Foreign_key
When a foreign key constraint is defined, it enforces a set of rules to maintain referential integrity. For example, it ensures that records cannot be added to the referencing table unless a corresponding record exists in the referenced table. Additionally, actions such as deleting or updating records are often restricted to preserve the integrity of the relationship. Common actions triggered by foreign key constraints include cascading deletes or updates, where changes made in the referenced table automatically propagate to the referencing table. This ensures consistency across related data.
https://www.sqlshack.com/sql-foreign-key-constraint-examples/
The use of foreign key constraints is crucial for preventing the introduction of orphan records, which are records that reference nonexistent data. By linking tables in a meaningful way, foreign key constraints also help optimize database queries by providing a clear structure for relationships between data sets. For example, in a database containing tables for customers and orders, a foreign key in the orders table might reference the customer table, ensuring that every order is linked to a valid customer. This helps in maintaining data accuracy and streamlining query processing.
https://www.dataversity.net/understanding-foreign-key-constraints-in-relational-databases/
Foreign key