Referential integrity is a concept in relational database management that ensures the consistency and accuracy of data by enforcing relationships between tables. It guarantees that a foreign key in one table always refers to a valid primary key in another table, preventing orphaned records and maintaining the logical connections between related data.
Key Points:
- Foreign Key Constraints: Referential integrity is typically enforced through foreign key constraints, which ensure that a value in a foreign key column matches a value in the primary key column of the referenced table.
- Data Consistency: It helps maintain data consistency by ensuring that relationships between tables remain valid.
- Prevents Orphaned Records: By enforcing referential integrity, the database prevents orphaned records, which are records that reference non-existent entries in another table.
Example:
Consider two tables, orders and customers, where orders has a foreign key customer_id that references the primary key id in the customers table.
CREATE TABLE customers (
id INT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
In this example, referential integrity ensures that every customer_id in the orders table corresponds to a valid id in the customers table. If you try to insert an order with a customer_id that does not exist in the customers table, the database will reject the operation, thus maintaining referential integrity.