Junior
What is the role of a foreign key in relational databases?
sobes.tech AI
Answer from AI
A foreign key is a column or a set of columns in one table that references the primary key or a unique key in another table.
Its role is to ensure data integrity and establish relationships between tables:
- Referential integrity: Ensures that the values in the foreign key exist in the related primary or unique key of another table. This prevents "dangling" references.
- Defining relationships between tables: Shows how records in one table are related to records in another. This is the basis for JOIN operations in SQL.
- Action constraints: Allows setting rules for behavior when deleting or updating records in the parent table (e.g.,
ON DELETE CASCADEorON UPDATE RESTRICT).
Example:
- The
orderstable contains a foreign keycustomer_id, which references the primary keyidin thecustomerstable. - This guarantees that each order is associated with an existing customer.