Can't drop table: A foreign key constraint fails - mysql

In MySQL I want to drop a table.
I tried a lot things but I keep getting the error that the table named bericht can't be dropped. This is the error I'm getting:
#1217 - Cannot delete or update a parent row: a foreign key constraint fails
How do I drop this table?

This should do the trick:
SET FOREIGN_KEY_CHECKS=0; DROP TABLE bericht; SET FOREIGN_KEY_CHECKS=1;
As others point out, this is almost never what you want, even though it's whats asked in the question. A more safe solution is to delete the tables depending on bericht before deleting bericht. See CloudyMarble answer on how to do that. I use bash and the method in my post to drop all tables in a database when I don't want to or can't delete and recreate the database itself.
The #1217 error happens when other tables has foreign key constraints to the table you are trying to delete and you are using the InnoDB database engine. This solution temporarily disables checking the restraints and then re-enables them. Read the documentation for more. Be sure to delete foreign key restraints and fields in tables depending on bericht, otherwise you might leave your database in a broken state.

Try this:
SELECT *
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'YourTable';
This should deliver you which Tables have references to the table you want to drop, once you drop these references, or the datasets which reference datasets in this table you will be able to drop the table

But fortunately, with the MySQL FOREIGN_KEY_CHECKS variable, you don't have to worry about the order of your DROP TABLE statements at all, and you can write them in any order you like -- even the exact opposite -- like this:
SET FOREIGN_KEY_CHECKS = 0;
drop table if exists customers;
drop table if exists orders;
drop table if exists order_details;
SET FOREIGN_KEY_CHECKS = 1;
For more clarification, check out the link below:
http://alvinalexander.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys/

Use show create table tbl_name to view the foreign keys
You can use this syntax to drop a foreign key:
ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol
There's also more information here (see Frank Vanderhallen post):
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

This probably has the same table to other schema the reason why you're getting that error.
You need to drop first the child row then the parent row.

I realize this is stale for a while and an answer had been selected, but how about the alternative to allow the foreign key to be NULL and then choose ON DELETE SET NULL.
Basically, your table should be changed like so:
ALTER TABLE 'bericht'
DROP FOREIGN KEY 'your_foreign_key';
ALTER TABLE 'bericht'
ADD CONSTRAINT 'your_foreign_key' FOREIGN KEY ('column_foreign_key') REFERENCES 'other_table' ('column_parent_key') ON UPDATE CASCADE ON DELETE SET NULL;
Personally I would recommend using both "ON UPDATE CASCADE" as well as "ON DELETE SET NULL" to avoid unnecessary complications, however your set up may dictate a different approach.
Hope this helps.

Related

Deleting one of two foreign keys in a MySQL table

I mistakenly added two foreign keys in one table in MySQL even though I proceeded in the described manner to create one foreign key only. But that aside, the problem is that I need to remove the foreign key which is NOHOW related to the main table in the database which the primary keys are referenced from.
That is, I need to remove the field CId from customer table.
Tables' image
You may need to first use
SET FOREIGN_KEY_CHECKS=0;
then you can drop the foreign key
ALTER TABLE <TABLE_NAME> DROP CONSTRAINT <FOREIGN_KEY_NAME>
And then make sure you set foreign keys back using
SET FOREIGN_KEY_CHECKS=1;

DROP FOREIGN KEY not working

On PHPMyAdmin, I would like to DROP a FOREIGN KEY with
ALTER TABLE information DROP FOREIGN KEY IDX_29791883B30676A7
Because when I do the next query it's not working:
ALTER TABLE information DROP INDEX IDX_29791883B30676A7
Cannot drop index 'IDX_29791883B30676A7': needed in a foreign key constraint
However, the second query as the error that the index is use as foreigner key.
Fine, but when I do the first query I get this error:
Can't DROP 'IDX_29791883B30676A7'; check that column/key exists
So the questions are:
How do I acually check that,
How can I finally drop that key.
Foreign keys by default are prefixed with 'FK' not 'IDX'. You are trying to remove an index instead of a foreign key. You mentioned that the foreign key is: FK_29791883B30676A7 so the correct way to remove it will be:
ALTER TABLE information DROP FOREIGN KEY FK_29791883B30676A7
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
I have the same problem with foreign keys, well I found a solution to removing constraint. For first take a look at:
SHOW CREATE TABLE information;
You will found the name of the rule, and then just drop it:
ALTER TABLE information DROP CONSTRAINT `name_of_rule`;
Try this
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE information DROP FOREIGN KEY IDX_29791883B30676A7;
ALTER TABLE information DROP INDEX IDX_29791883B30676A7;
SET FOREIGN_KEY_CHECKS=1;

How to remove constraints from my MySQL table?

I want to remove constraints from my table. My query is:
ALTER TABLE `tbl_magazine_issue`
DROP CONSTRAINT `FK_tbl_magazine_issue_mst_users`
But I got an error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'constraint FK_tbl_magazine_issue_mst_users' at line 1
Mysql has a special syntax for dropping foreign key constraints:
ALTER TABLE tbl_magazine_issue
DROP FOREIGN KEY FK_tbl_magazine_issue_mst_users
I had the same problem and I got to solve with this code:
ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;
ALTER TABLE `table_name` DROP INDEX `id_name_fk`;
There is no such thing as DROP CONSTRAINT in MySQL. In your case you could use DROP FOREIGN KEY instead.
If the constraint is not a foreign key, eg. one added using 'UNIQUE CONSTRAINT (colA, colB)' then it is an index that can be dropped using ALTER TABLE ... DROP INDEX ...
To add a little to Robert Knight's answer, since the title of the post itself doesn't mention foreign keys (and since his doesn't have complete code samples and since SO's comment code blocks don't show as well as the answers' code blocks), I'll add this for unique constraints. Either of these work to drop the constraint:
ALTER TABLE `table_name` DROP KEY `uc_name`;
or
ALTER TABLE `table_name` DROP INDEX `uc_name`;
Also nice, you can temporarily disable all foreign key checks from a mysql database:
SET FOREIGN_KEY_CHECKS=0;
And to enable it again:
SET FOREIGN_KEY_CHECKS=1;
Some ORM's or frameworks use a different naming convention for foreign keys than the default FK_[parent table]_[referenced table]_[referencing field], because they can be altered.
Laravel for example uses [parent table]_[referencing field]_foreign as naming convention. You can show the names of the foreign keys by using this query, as shown here:
SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = '<database>' AND REFERENCED_TABLE_NAME = '<table>';
Then remove the foreign key by running the before mentioned DROP FOREIGN KEY query and its proper name.
The simplest way to remove constraint is to use syntax ALTER TABLE tbl_name DROP CONSTRAINT symbol; introduced in MySQL 8.0.19:
As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name
ALTER TABLE tbl_magazine_issue DROP CONSTRAINT FK_tbl_magazine_issue_mst_users;
db<>fiddle demo
For those that come here using MariaDB:
Note that MariaDB allows DROP CONSTRAINT statements in general, for example for dropping check constraints:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
https://mariadb.com/kb/en/library/alter-table/
Go to structure view of the table
You will see 2 option at top a.Table structure b.Relation view.
Now click on Relation view , here you can drop your foreign key constraint. You will get all relation here.
In MySQL you have to specify what kind of constraint you want to remove:
Example:
CONSTRAINT `shop_ibfk_1` FOREIGN KEY (`fb_user_id`) REFERENCES `fb_user` (`id`),
CONSTRAINT `shop_chk_1` CHECK ((`import_lock` in (0,1)))
the first one you would remove with:
alter mytable shop drop FOREIGN KEY `shop_ibfk_1`;
the second one with
alter mytable drop CHECK `shop_chk_1`;
this will works on MySQL to drop constraints
alter table tablename drop primary key;
alter table tablename drop foreign key;

Failing to drop or truncate a table

I tried every thing to truncate a table, but I always have the same message :
Cannot delete or update a parent row: a foreign key constraint fails (`mybdd`.`c_member`, CONSTRAINT `fk_cm_c_id` FOREIGN KEY (`c_id`) REFERENCES `comment` (`c_id`))
Looking some posts on this site I tried this :
ALTER TABLE comment
ADD CONSTRAINT c_member FOREIGN KEY (c_id)
REFERENCES comment (c_id);
But it doens't work :
Can't create table 'mybdd.#sql-2ee0_3769864' (errno: 150){"success":false,"error":"
1005 - Can't create table 'sameditrbdd.#sql-2ee0_3769864' (errno: 150)</div>"}
How can I do that ?
You need to delete all references to the table, including all foreign key constraints and indexes, before you can drop a table.
Foreign key constraints can also prevent you from deleting specific rows.
Alternatively, you can turn off foreign key checks, but then setting them back on again will likely result in errors or unpredictable behavior (because your constraints are violated by the data in the data base).
You can use:
SET foreign_key_checks = 0;
DROP <your_table>
SET foreign_key_checks = 1;
Very likely some people or their process holding your table hostage!!!
You should try to kill them addressing them by their spid #!
To see who is holding your table hostage, you open up your query analyser to run
execute sp_who2 'active' -- under the database of interest
Then, make your own judgment whether it is OK to kill them or not, or call those who logged in.
To kill, just do
kill 999 -- your spid # found in that table returned by above command
After that, try to truncate or drop again!
Best luck!!!

Bogus foreign key constraint fail

I get this error message:
ERROR 1217 (23000) at line 40: Cannot
delete or update a parent row: a
foreign key constraint fails
... when I try to drop a table:
DROP TABLE IF EXISTS `area`;
... defined like this:
CREATE TABLE `area` (
`area_id` char(3) COLLATE utf8_spanish_ci NOT NULL,
`nombre_area` varchar(30) COLLATE utf8_spanish_ci NOT NULL,
`descripcion_area` varchar(100) COLLATE utf8_spanish_ci NOT NULL,
PRIMARY KEY (`area_id`),
UNIQUE KEY `nombre_area_UNIQUE` (`nombre_area`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;
The funny thing is that I already dropped all other tables in the schema that have foreign keys against area. Actually, the database is empty except for the area table.
How can it possibly have child rows if there isn't any other object in the database? As far as I know, InnoDB doesn't allow foreign keys on other schemas, does it?
(I can even run a RENAME TABLE area TO something_else command :-?)
On demand, now as an answer...
When using MySQL Query Browser or phpMyAdmin, it appears that a new connection is opened for each query (bugs.mysql.com/bug.php?id=8280), making it neccessary to write all the drop statements in one query, eg.
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE my_first_table_to_drop;
DROP TABLE my_second_table_to_drop;
SET FOREIGN_KEY_CHECKS=1;
Where the SET FOREIGN_KEY_CHECKS=1 serves as an extra security measure...
Two possibilities:
There is a table within another schema ("database" in mysql terminology) which has a FK reference
The innodb internal data dictionary is out of sync with the mysql one.
You can see which table it was (one of them, anyway) by doing a "SHOW ENGINE INNODB STATUS" after the drop fails.
If it turns out to be the latter case, I'd dump and restore the whole server if you can.
MySQL 5.1 and above will give you the name of the table with the FK in the error message.
Disable foreign key checking
SET FOREIGN_KEY_CHECKS=0
from this blog:
You can temporarily disable foreign key checks:
SET FOREIGN_KEY_CHECKS=0;
Just be sure to restore them once you’re done messing around:
SET FOREIGN_KEY_CHECKS=1;
hopefully its work
SET foreign_key_checks = 0;
DROP TABLE table name;
SET foreign_key_checks = 1;
On Rails, one can do the following using the rails console:
connection = ActiveRecord::Base.connection
connection.execute("SET FOREIGN_KEY_CHECKS=0;")
Maybe you received an error when working with this table before. You can rename the table and try to remove it again.
ALTER TABLE `area` RENAME TO `area2`;
DROP TABLE IF EXISTS `area2`;
i found an easy solution, export the database, edit it what you want to edit in a text editor, then import it. Done
Cannot delete or update a parent row: a foreign key constraint fails (table1.user_role, CONSTRAINT FK143BF46A8dsfsfds##5A6BD60 FOREIGN KEY (user_id) REFERENCES user (id))
What i did in two simple steps . first i delete the child row in child table like
mysql> delete from table2 where role_id = 2 && user_id =20;
Query OK, 1 row affected (0.10 sec)
and second step as deleting the parent
delete from table1 where id = 20;
Query OK, 1 row affected (0.12 sec)
By this i solve the Problem which means Delete Child then Delete parent
i Hope You got it. :)