I'm on a MySQL database.
I'm doing this, but it doesn't work.
ALTER TABLE `object` DROP FOREIGN KEY IF EXISTS `object_ibfk_1`;
I've tried to put this IF EXISTS wherever I could. How can check if foreign key is exists before drop it?
I'm on a MySQL database.
I'm doing this, but it doesn't work.
ALTER TABLE `object` DROP FOREIGN KEY IF EXISTS `object_ibfk_1`;
I've tried to put this IF EXISTS wherever I could. How can check if foreign key is exists before drop it?
When you create a foreign key constraint, mysql will automatically create an index on the referenced column. The example above shows how to check for an index in the INFORMATION_SCHEMA, but there is much more information for you to check out in the information schema. Your index name seems to indicate that it was created for a FK, so you'd have to drop the FK first, then drop the index. If you create the foreign key again, mysql will create the index again. It needs an index to enforce referential integrity without having to do a table scan.
If your intention was to create a new index that contains the same column, you'd have to create that index first (with this column, the one that will be used as a FK, being the first in the list of columns specified for the index). Now you can add your FK back and mysql will be happy to use the new index without creating another one.
Edit: to view indexes quickly simply execute SHOW INDEXES FROM myTable;
If you want to drop foreign key if it exists and do not want to use procedures you can do it this way (for MySQL) :
If there is foreign key we put alter table statement in variable and if there isn't we put a dummy statement. And then we execute it.
For greater re-usability, you would indeed want to use a stored procedure. Run this code once on your desired DB:
Thereafter, you can always replace this:
with this:
Your script should then run smoothly whether
object_ibfk_1
actually exists or not.A lot of credit due to: http://simpcode.blogspot.com.ng/2015/03/mysql-drop-foreign-key-if-exists.html
Which Database you are using??
If SQL Server
In the current version of Mariadb 10.1.26 (new Mysql), your query works:
Key:
MUL
Key:
<NULL>
Similar discussion: How do I drop a foreign key constraint only if it exists in sql server?
is very useful and not mentioned yet here.