Junior — Middle
What is the role of a foreign key in a database and why is it important?
sobes.tech AI
Answer from AI
A foreign key in a database is a field or a set of fields in one table that references the primary key of another table. Its role is to ensure data integrity and to link related records between tables.
Why is this important:
- It guarantees that the values in the foreign key exist in the related table (referential integrity).
- It allows implementing relationships between tables (e.g., one-to-many).
- It ensures data correctness and prevents the appearance of "dangling" links.
Example: there is an Orders table with a CustomerId field, which is a foreign key referencing the Id in the Customers table. This guarantees that each order is associated with an existing customer.