59

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.

4 Answers 4

79

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';

You can also add (to the WHERE clause) if you have more than one table called My_Table in different schemas.

AND TABLE_SCHEMA = 'My_Database';

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

ALTER TABLE My_Table DROP FOREIGN KEY FK_constraint_name;  

The FK_constraint_name is obtained from the CONSTRAINT_NAME field highlighted in the query above.

References: 1 & 2.

0
4

In MySql 5.7. You can find table relations and relations rules.

SELECT
  DISTINCT a.TABLE_NAME,
  a.CONSTRAINT_NAME,
  b.DELETE_RULE,
  b.UPDATE_RULE,
  a.REFERENCED_TABLE_NAME,
  a.COLUMN_NAME,
  a.REFERENCED_COLUMN_NAME,
  a.TABLE_SCHEMA
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE a
JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS b USING (CONSTRAINT_NAME)
WHERE
    a.TABLE_SCHEMA = "DATABASE_NAME" AND
    a.REFERENCED_TABLE_NAME = 'TABLE_NAME'
ORDER BY a.TABLE_NAME ASC;
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
2
  • Get the following error upon running this query - Unknown column 'f' in 'where clause'
    – Ghos3t
    Mar 31, 2021 at 21:11
  • @ghos3t you don't need the constraint_name = f, that's just extra, just remove that part.
    – spen.smith
    Apr 10, 2021 at 4:22
-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 >> ';


0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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