Course contentsShow
← Data Science
Lesson 1055 of 2,14527. Database Design and OptimizationFree lesson

What is Referential Integrity?

Definition of referential integrity and why it ensures foreign keys correctly reference primary keys in related tables.

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:

  1. Rejecting invalid inserts: You can't add a row with a foreign key value that doesn't exist in the parent table
  2. Controlling deletes: Cascading actions (DELETE and UPDATE) you learned about help maintain integrity when parent records change
  3. 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.