Referential integrity is a property of a relational database that ensures relationships between tables remain consistent. It guarantees that a foreign key value in one table must either match a primary key value in another table or be null. This helps maintain the accuracy and reliability of the data within the database.
Key Points of Referential Integrity:
-
Consistency: It ensures that relationships between tables are valid and that data is consistent across the database.
-
Foreign Key Constraints: Referential integrity is enforced through foreign key constraints, which link a column in one table to the primary key of another table.
-
Prevention of Orphan Records: It prevents the creation of orphan records in the child table, which would occur if a foreign key references a non-existent primary key in the parent table.
-
Cascading Actions: Referential integrity can be maintained through cascading actions, such as automatically updating or deleting related records when a record in the parent table is modified.
Example
Consider two tables: customers and orders. If the orders table has a foreign key that references the customer_id in the customers table, referential integrity ensures that every order must be associated with a valid customer. If a customer is deleted, the database can either prevent the deletion if there are existing orders or cascade the deletion to remove those orders as well, depending on how the foreign key constraint is defined.
