Skip to content
Advertisement

How to drop a column with foreign key in MySQL?

Let’s say I used the following structure to create a table:

Now I want to add DELETE CASCADE for the foreign key and I found that I can achieve it by dropping the column(column with foreign key) and adding it again with DELETE CASCADE property on alter table statement.

But when I tried:

So I need to remove foreign key constraint first with:

As you saw above table was created without giving the name for constraint. I am having trouble to drop it. So what should be done ? I need the way of dropping the column along with foreign key constraint:)

Advertisement

Answer

Finally, I found the solution, We can use information_schema to retrieve the name of a foreign key and can use the name event constraint name is not set explicitly as shown above.

As of MySQL docs: INFORMATION_SCHEMA provides access to database metadata, information about the MySQL server such as the name of a database or table, the data type of a column, or access privileges. Other terms that are sometimes used for this information are data dictionary and system catalog.

For more information visit: https://dev.mysql.com/doc/refman/8.0/en/information-schema.html

So we can do something like:

Where INNODB denotes a storage engine, for more information visit: https://dev.mysql.com/doc/refman/8.0/en/storage-engines.html

After executing the query we can get the result something like:

As we can see in the ID contains the name of database/foreign key name so finally we can do something like

From last row and finally we can drop the column easily 🙂

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement