Alter Table To Remove Foreign Key Or Add DELETE CASCADE (MySQL)

5 5Balloons Tech
  • Laravel
    • Learn Laravel
    • Livewire Tutorials
    • Laravel Dusk
  • Frontend
    • TailwindCSS
    • Bootstrap
    • AlpineJS
  • Components
    • Livewire Components
    • TailwindCSS Components
  • Courses
    • Laravel Dusk
    • AlpineJS
  • About
    • About Me
    • My Stack
    • Advertise
  • Laravel
    • Learn Laravel
    • Livewire Tutorials
    • Laravel Dusk
  • Frontend
    • TailwindCSS
    • Bootstrap
    • AlpineJS
  • Components
    • Livewire Components
    • TailwindCSS Components
  • Courses
    • Laravel Dusk
    • AlpineJS
  • About
    • About Me
    • My Stack
    • Advertise
Search Search

SQL

Alter table to remove Foreign Key or add DELETE CASCADE (MySQL) SQL Photo of tgugnani

tgugnani

Dec 20, 2016

Step 1 : Get the Foreign Key Name.

SHOW CREATE TABLE tableName;

Note the name of Foreign key (which is mostly auto generated) output will look something like

CONSTRAINT `FK4C5B93445F11A0B7` FOREIGN KEY (ID`) REFERENCES `PARENT_TABLE` (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

Step 2: Drop the Foreign Key.

Alter table tableName drop foreign key FK4C5B93445F11A0B7

Dont worry, this will not harm your data. It will just remove the constraint. You can add it back later

Step 3: Now add the foreign key constraint back again, this time with ON DELETE CASCADE

alter table tableName add foreign key (ID) references PARENT_TABLE(ID) on DELETE CASCADE

There you Go! You can run SHOW CREATE TABLE tableName; to verify on DELETE CASCADE

screen-shot-2016-12-20-at-12-16-09-pm

Comments

Tag » Add Constraint On Delete Cascade Mysql