Sobes.tech
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 parent will also delete all related records in child with the same parent_id.
  • Changing id in parent will automatically update the corresponding parent_id in child.

This is convenient for maintaining data integrity without writing additional code.