45

How to see foreign keys related to a table in MySql?

Background : I wanted to drop a table in MySql which has a foreign key constraint. When I do it I get this:

Error Code: 1217. Cannot delete or update a parent row: a foreign key constraint fails

How can I drop foreign keys related to the table leaving others.

58

Firstly, find out your FOREIGN KEY constraint name in this way:

SELECT
  TABLE_NAME,
  COLUMN_NAME,
  CONSTRAINT_NAME,   -- <<-- the one you want! 
  REFERENCED_TABLE_NAME,
  REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'My_Table';

And then you can remove the named constraint in the following way:

ALTER TABLE My_Table DROP FOREIGN KEY My_Table_Constraint;

References: 1 & 2.

As suggested by @SteffenWinkler in comments, if there is more than one table of that name in different schemas/databases, you can add a further predicate to your where clause:

AND TABLE_SCHEMA = 'My_Database';
2

Editied the Query above. Changed Referenced Table name to Table Name as Referenced Table name is the table which is being referenced and hence the result of the original query wont show you the foreign keys on your table.

SELECT
  TABLE_NAME,
  COLUMN_NAME,
  CONSTRAINT_NAME,   -- <<-- the one you want! 
  REFERENCED_TABLE_NAME,
  REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  Table_name = 'case_qualitycontrolcase' and constraint_name = f
-1

You can directly execute this query's output to drop the constraint of referenced table.



select concat('ALTER TABLE ' ,CONSTRAINT_SCHEMA,'.',TABLE_NAME,' DROP FOREIGN KEY ' ,CONSTRAINT_NAME ,';' )
from  information_schema.REFERENTIAL_CONSTRAINTS  
where REFERENCED_TABLE_NAME='<<table to be dropped >> ';


  • This adds nothing to the existing answers. – Colin 't Hart Dec 3 '19 at 12:21
  • Thanks for review, I hope now it adds to answer – JYOTI RAJAI Dec 3 '19 at 13:13
-3
SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = '<database>' AND
  REFERENCED_TABLE_NAME = '<table>';
  • This adds nothing to the existing answers. – Colin 't Hart Dec 3 '19 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.