Junior — Middle
What is the main purpose of using foreign keys in relational databases?
sobes.tech AI
Answer from AI
Foreign keys in relational databases serve to ensure data integrity and establish relationships between tables.
The main purposes of using foreign keys:
- To guarantee that the value in a column (or set of columns) in one table corresponds to an existing value in another table (usually the primary key).
- To ensure referential integrity, preventing the appearance of "dangling" references to non-existent records.
- To allow the database to automatically control update and delete operations on related records (e.g., cascade delete).
Example: a table Orders may have a foreign key customer_id that references id in the Customers table. This guarantees that each order is associated with an existing customer.