Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DROP all foreign keys in MYSQL database

Tags:

mysql

Foreign keys are causing me too many problems modifying an database structure to meet new requirements - I want to modify primary keys but it seems I can't when foreign keys reference the table in question (I think because MySQL drops the table and re-creates).

So while I work on the DB, I'd like to simply remove all the foreign keys and re-create them later. Is there a neat way to do so?

like image 306
Mr. Boy Avatar asked Dec 05 '12 22:12

Mr. Boy


People also ask

How do I drop all foreign keys in MySQL?

Dropping Foreign Key Constraints You can drop a foreign key constraint using the following ALTER TABLE syntax: ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol; If the FOREIGN KEY clause defined a CONSTRAINT name when you created the constraint, you can refer to that name to drop the foreign key constraint.

Can we write a query to drop foreign key?

Description. Once a foreign key has been created, you may find that you wish to drop the foreign key from the table. You can do this with the ALTER TABLE statement in SQL Server (Transact-SQL).


1 Answers

Run

SELECT concat('ALTER TABLE ', TABLE_NAME, ' DROP FOREIGN KEY ', CONSTRAINT_NAME, ';')  FROM information_schema.key_column_usage  WHERE CONSTRAINT_SCHEMA = 'db_name'  AND referenced_table_name IS NOT NULL; 

and run the output.

like image 87
Zoozy Avatar answered Sep 19 '22 14:09

Zoozy