Middle
What is referential integrity?
sobes.tech AI
Answer from AI
Referential Integrity is a property of data in a relational database that guarantees that links between tables remain valid. It prevents the following issues:
- Deletion of a row from the "parent" table that is referenced by rows in the "child" table.
- Changing the primary key in the "parent" table that is referenced by rows in the "child" table, without updating those references accordingly.
- Inserting a row into the "child" table with a reference to a non-existent primary key in the "parent" table.
It is implemented using foreign keys (FOREIGN KEY).
Examples of constraints for foreign keys:
- ON DELETE CASCADE: When a row in the parent table is deleted, the corresponding rows in the child table are also deleted.
- ON DELETE SET NULL: When a row in the parent table is deleted, the corresponding foreign key in the child table is set to NULL.
- ON DELETE RESTRICT: Deletion of a row in the parent table is prohibited if there are references to it in the child table.
- ON UPDATE CASCADE: When the primary key in the parent table is updated, the corresponding foreign keys in the child table are also updated.
-- Example of a "users" table (parent)
CREATE TABLE users (
user_id INT PRIMARY KEY,
username VARCHAR(255) NOT NULL
);
-- Example of an "orders" table (child) with a foreign key
CREATE TABLE orders (
order_id INT PRIMARY KEY,
user_id INT,
order_date DATE,
FOREIGN KEY (user_id) REFERENCES users(user_id)
ON DELETE CASCADE /* Example of constraint usage */
ON UPDATE CASCADE /* Example of constraint usage */
);