How do I implement cascade update

In MySQL, a cascade update can be implemented using foreign keys with the "ON UPDATE CASCADE" option. This means that if a primary key is updated in the parent table, the corresponding foreign keys in the child table will automatically be updated to reflect that change.

Example of Cascade Update in MySQL

-- Creating a parent table CREATE TABLE departments ( id INT PRIMARY KEY, name VARCHAR(50) ); -- Creating a child table with foreign key referencing the parent table CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(50), department_id INT, FOREIGN KEY (department_id) REFERENCES departments(id) ON UPDATE CASCADE ); -- Inserting data into the parent table INSERT INTO departments (id, name) VALUES (1, 'Human Resources'), (2, 'IT'); -- Inserting data into the child table INSERT INTO employees (id, name, department_id) VALUES (1, 'John Doe', 1), (2, 'Jane Smith', 2); -- Updating the primary key in the parent table UPDATE departments SET id = 3 WHERE id = 1; -- The corresponding foreign key in the child table will automatically be updated -- You can check the updated employees table SELECT * FROM employees;

MySQL cascade update foreign key ON UPDATE CASCADE database management