Other Tools By Katy:

ON DELETE Cascade (Remove child records when parent records deleted)

If you haven’t created the child table you can run the following SQL command:


CREATE TABLE ChildTable (
    ChildID INT PRIMARY KEY AUTO_INCREMENT,
    ParentID INT,
    ChildFields VARCHAR(255),
    -- Add fields as required
    -- Define the foreign key and the cascade rule
    FOREIGN KEY (ParentID) 
        REFERENCES ParentTable(ParentID) 
        ON DELETE CASCADE
);

If you have already created the Child Table you can run an alter statement:


ALTER TABLE ChildTable
ADD CONSTRAINT fk_ParentTable_link
FOREIGN KEY (ParentID) 
REFERENCES ParentTable(ParentID) 
ON DELETE CASCADE;
Disclaimer: The code on this website is provided "as is" and comes with no warranty. The author of this website does not accept any responsibility for issues arising from the use of code on this website. Before making any significant changes, ensure you take a backup of all files and do not work directly on a live/production website without thoughly testing your changes first.

Leave a Reply

Your email address will not be published. Required fields are marked *