Junior — Middle
What is the role of a foreign key in a relational database?
sobes.tech AI
Answer from AI
A foreign key in a relational database is used to ensure referential integrity between two tables. It points to the primary key of another table and guarantees that the values in the foreign key column correspond to existing values in the related table.
Role of the foreign key:
- Ensures a relationship between tables (e.g., orders and customers).
- Prevents insertion of incorrect data that does not match any entry in the related table.
- Allows cascading updates or deletions of related records (if configured).
Example: In the Orders table, there is a customer_id column, which is a foreign key referencing the id in the Customers table. This guarantees that each order is linked to an existing customer.