What is Referential Integrity?
You'll learn what referential integrity means and why it's essential for maintaining accurate relationships between database tables.
The Core Idea
Referential integrity is a database rule that ensures every foreign key value in one table correctly points to an existing primary key value in another table—or is NULL (if allowed). In other words, you cannot reference something that doesn't exist.
Think of it like a library catalog system: if a book record references an author ID, that author must actually exist in the authors table. You can't have books pointing to phantom authors who aren't in your database.
Why It Matters
Referential integrity prevents "orphaned" records and maintains data consistency. Without it, you could have:
- Orders referencing customers who were deleted
- Products linked to non-existent categories
- Transactions pointing to invalid account IDs
These broken references create unreliable data and make queries unpredictable.
How Foreign Key Constraints Enforce It
When you define a foreign key constraint (as you learned previously), the database automatically enforces referential integrity by:
- Rejecting invalid inserts: You can't add a row with a foreign key value that doesn't exist in the parent table
- Controlling deletes: Cascading actions (DELETE and UPDATE) you learned about help maintain integrity when parent records change
- Validating updates: Changes to foreign key values are checked against the parent table
The Relationship to What You've Learned
This concept ties together primary keys (which uniquely identify rows), foreign keys (which create relationships), and cascading actions (which help maintain integrity during changes).
Key Takeaway: Referential integrity ensures that foreign keys always point to valid primary keys, preventing broken relationships and maintaining reliable data throughout your database.