A foreign key links records in one table to records in another. An order table has a customer_id field. That field is a foreign key pointing to the customer table's primary key. The link ensures that every order belongs to a real customer. Without it, orders could reference customers that do not exist. The database enforces the relationship.
Foreign keys do more than document relationships. They enforce referential integrity. If you try to insert an order with a customer_id that does not exist in the customer table, the database rejects it. If you try to delete a customer who has orders, the database either blocks the deletion or cascades it depending on the rule. That enforcement prevents orphaned records and inconsistent data. Foreign keys also help query performance. The database can use the relationship to optimize joins. Not all databases enforce foreign keys. Some NoSQL databases leave referential integrity to the application. That gives developers more flexibility but also more responsibility. The application must ensure that references are valid. If it fails, the data becomes inconsistent. Foreign keys are a constraint. Constraints are inconvenient until they prevent a disaster.
Foreign key rules
- Restrict — block deletion if references exist
- Cascade — delete or update referencing records automatically
- Set null — set the foreign key to null on deletion
- No action — allow the operation and check later
A foreign key is a link and a guarantee. The link connects tables. The guarantee keeps them consistent.
Comments
No comments yet. Be the first to share a thought.
Leave a comment