Databases & Data Storage
Foreign Key
Definition
A foreign key is a column or a set of columns in a table that refers to the primary key of another table. It acts as a cross-reference between tables and establishes a link between them.
Why It Matters
Foreign keys are what put the "relation" in "relational database." They enforce referential integrity, ensuring that a record in one table cannot point to a non-existent record in another table.
Contextual Example
An `Orders` table has a `CustomerID` column that is a foreign key pointing to the `UserID` primary key in the `Users` table. This ensures that every order is associated with a real, existing customer.
Common Misunderstandings
- A foreign key constraint prevents you from deleting a user if they have existing orders, or from creating an order for a user who does not exist.
- They are the foundation of database joins.