Ένα ξένο κλειδί συνδέει εγγραφές σε έναν πίνακα με εγγραφές σε έναν άλλο. Ένας πίνακας παραγγελιών έχει ένα πεδίο customer_id. Αυτό το πεδίο είναι ένα ξένο κλειδί που δείχνει στο πρωτεύον κλειδί του πίνακα πελατών. Ο σύνδεσμος διασφαλίζει ότι κάθε παραγγελία ανήκει σε έναν πραγματικό πελάτη. Χωρίς αυτόν, οι παραγγελίες θα μπορούσαν να αναφέρονται σε πελάτες που δεν υπάρχουν. Η βάση δεδομένων επιβάλλει τη σχέση.
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