Junior — Middle
Can you explain how cascade delete and update operations are implemented in SQL?
sobes.tech AI
Answer from AI
Cascade delete and update in SQL are implemented using foreign key constraints with the options ON DELETE CASCADE and ON UPDATE CASCADE.
This means that when a record in the parent table is deleted or updated, related records in the child tables are automatically deleted or updated.
Example of creating tables with cascade delete and update:
CREATE TABLE parent (
id INT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE child (
id INT PRIMARY KEY,
parent_id INT,
description VARCHAR(100),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
In this example:
- Deleting a record from
parentwill also delete all related records inchildwith the sameparent_id. - Changing
idinparentwill automatically update the correspondingparent_idinchild.
This is convenient for maintaining data integrity without writing additional code.