MySQL - How to check if exist foreign key
In MySQL, the "IF EXIST" clause doesn't function when checking a foreign key. There is only one method I know to perform this check.
Information regarding constraints is stored in the general MySQL table "information_schema.TABLE_CONSTRAINTS".
The "TABLE_NAME" column indicates the table where the constraint exists.
The "CONSTRAINT_NAME" column represents the name of your constraint.
The "CONSTRAINT_TYPE" column defines the type of your constraint; in our case, it is a "FOREIGN KEY".
So, for example, if you want to check all foreign keys in your table:
SELECT *
FROM information_schema.TABLE_CONSTRAINTS
WHERE TABLE_NAME='name_of_your_table' AND CONSTRAINT_TYPE='FOREIGN KEY';
In my case it shows:
CONSTRAINT_CATALOG | CONSTRAINT_SCHEMA | CONSTRAINT_NAME | TABLE_SCHEMA | TABLE_NAME | CONSTRAINT_TYPE |
---|---|---|---|---|---|
def | test | FK_9CA1B3534C397118 | test | tblproducts | FOREIGN KEY |
def | test | FK_1C5BFC7ABF396750 | test | tblcontacts | FOREIGN KEY |
I hope it helps you :)
Comments