Search code examples
mysqlsqlindexingforeign-keysforeign-key-relationship

Mysql Foreign Key Creation


I am trying to add foreign key to my table with this script:

ALTER TABLE PRM_CTY
ADD CONSTRAINT fk_PRM_CTY_PRNT_CTY
FOREIGN KEY (PRNT_CTY_ID)
REFERENCES PRM_CTY(ID);

this code work but foreign key doesnt creat. instead of this a new index is created named fk_PRM_CTY_PRNT_CTY.

my foreign key returns an index help me why it happens?


Solution

  • MySQL automatically creates an index to support each foreign key constraint, unless a suitable one already exists. The creation of an index suggests -- but does not prove -- that the constraint was successfully created. It is not a sign that constraint creation failed. To verify that the constraint exists, try to insert a row that violates it.

    Edited to add:

    Note, too, that you should be using the InnoDB storage engine if you want enforcement of foreign key constraints. The default default was MyISAM prior to MySQL 5.5, and that engine is still available, so if you were not aware of this issue then that could be what you are using.