What is the purpose of a foreign key in a relational database?
a) To ensure that each row is unique in the table
b) To establish a relationship between two tables
c) To speed up query performance
d) To store large objects
Answer:
b) To establish a relationship between two tables
Explanation:
A foreign key is a column or a set of columns in one table that refers to the primary key of another table. It is used to establish and enforce a relationship between the two tables, ensuring referential integrity.
Foreign keys help maintain consistency by ensuring that values in the referencing table (child) correspond to valid records in the referenced table (parent). This prevents orphaned records and ensures logical relationships are upheld.
For example, in an “orders” table, a foreign key can link to a “customers” table, ensuring that every order corresponds to a valid customer.