If I create a foreign key constraint for table 'photos' in phpmyadmin, I later see that the constraint is named 'photos_ibfk_1', and the next constraint is called 'photos_ibfk_2', etc. From this I have gathered that [tablename]_ibfk_constraintIndex is the convention for DB constraints in MySQL. Is this correct? What does IBFK stand for?
-
6**ibfk** = ib (**I**nnoD**B**) fk (**f**oreign **k**ey) ... innodb foreign key – WebGuy Dec 22 '16 at 16:11
2 Answers
innodb foreign key. It's just short hand naming convention. You could call it asdfqwerty and the name would still work.
- 5,153
- 5
- 36
- 56
Although foreign key names can be anything, it's actually a good practice to follow the convention of putting the table name first.
The most important reason for this is that foreign key names must be unique within a database (contrarily to index names, which must only be unique within each table). So, by following this convention, foreign key names only have to be unique within each table.
Personally, I use the convention [table_name]_fk_[field_name].
In order to name your foreign keys, you will have to explicitly spell out the constraint on the table, instead of just the foreign key.
Simple method (automatic naming, will result in [table_name]_ibfk_[index]):
ALTER TABLE `[table_name]`
ADD FOREIGN KEY (`[field_name]`)
REFERENCES `[foreign_table_name]`(`[foreign_field_name]`);
Explicit method (will result in [table_name]_fk_[field_name]):
ALTER TABLE `[table_name]`
ADD CONSTRAINT `[table_name]_fk_[field_name]`
FOREIGN KEY (`[field_name]`)
REFERENCES `[foreign_table_name]`(`[foreign_field_name]`);
- 203
- 1
- 3
- 6
-
1Constraint names are not *globally unique* on the whole server -- only unique to the database. You can re-use the same constraint name on two different databases on the same server. – Brandon Jul 18 '19 at 21:46
-
-
Hello I'm a new comer to Mysql. I'm confused about words "The most important reason for this is that foreign key names must be unique within a database", so ```[table_name]_ibfk_[index]``` is **foreign key names**? – Archsx Dec 05 '20 at 10:29
-
1@Archsx: Yes, that's the name of the constraint. Foreign keys are one type of constraint, but there are also others, like unique keys. – Marco Roy Dec 10 '20 at 17:40