Skip to content

MySQL – How to drop all Foreign Keys on a table

I recently was working with a 3rd party DB that was designed well and used lots of foreign keys to enforce referential integrity. Unfortunately, the application that used the DB structure was very poorly written and caused all sorts of problems when the foreign keys were applied. I had to quickly remove all the foreign keys from about 160 tables. The code below will quickly create a script that removes all Foreign Keys from a database.

select concat(‘alter table ‘,table_schema,’.',table_name,’ DROP FOREIGN KEY ‘,constraint_name,’;') from information_schema.table_constraints
where constraint_type=’FOREIGN KEY’;

You can limit by schema by adding the line : AND table_schema rlike ‘Schema Name’

Remember, Foreign keys are only valid when using Innodb, MyISAM does not support foreign keys.

Share and Enjoy:
  • Digg
  • Yahoo! Buzz
  • del.icio.us
  • StumbleUpon
  • Facebook
  • LinkedIn
  • Technorati
  • Mixx
  • Google Bookmarks
  • email
  • Print

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*
CommentLuv Enabled