Does MySQL index foreign key columns automatically?

Does MySQL index foreign key columns automatically?


Yes, but only on innodb. Innodb is currently the only shipped table format that has foreign keys implemented.


Apparently an index is created automatically as specified in the link robert has posted.

InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. (This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.) index_name, if given, is used as described previously.

InnoDB and FOREIGN KEY Constraints


Yes, see InnoDB and FOREIGN KEY Constraints.


You don't get the index automatically if you do an ALTER TABLE (instead of CREATE TABLE), at least according to the docs (the link is for 5.1 but it's the same for 5.5):

[...] When you add a foreign key constraint to a table using ALTER TABLE, remember to create the required indexes first.


For those who are looking for quote from 5.7 docs:

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.