Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL foreign key question

Does defining a foreign key also defines a index? I have mysql v5.1.46 & I am looking at the MySQL Administrator tool and its shows the foreign key as an index, so I wanted to confirm?

like image 253
kapso Avatar asked Jul 18 '10 19:07

kapso


People also ask

What is a foreign key question?

Foreign KeysA foreign key column in a table points to a column with unique values in another table (often the primary key column) to create a way of cross-referencing the two tables.

Can two foreign keys in the same table reference the same primary key?

Yes, it is okay to have two fk to the same pk in one table.

Can foreign key have different name?

A foreign key can also have different column names than the primary key. The foreign key and primary key can also have different default values. However, since values in the referenced table must be unique, default values are not much used and are rarely used for columns that are part of a primary key.


1 Answers

  • If there already is a usable index (an index where the foreign key columns are listed as the first columns in the same order) then a new index is not created.
  • If there is no usable index then creating a foreign key also creates an index.

This is covered in the documentation.

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.

like image 114
Mark Byers Avatar answered Sep 27 '22 17:09

Mark Byers