1

I create the foreign key to one field in my table, the index was automatically created to that field. why the index was automatically created to foreign key fields?

Sunitha Bharathy
  • 97
  • 1
  • 3
  • 11

2 Answers2

1

The indices are created on foreign keys to improve performance. If you have a foreign key is common to want to get related items, an index allows you to quickly get these items. Also the conditions imposed on foreign keys (delete, update) take advantage of the index to work fast. Finally you need to perform integrity checks when creating foreign keys, this requires performing searches, these searches take advantage of the indexes.

Jhonathan
  • 1,611
  • 2
  • 13
  • 24
0

Foreign Key fields link to the contents of fields in other tables.

If we create a table like so:

Table Patient
  id 
  name
  address

And a table Illness

Table Illness
  id
  patient_id foreign key to patient.id
  description

MySQL checks to see if a foreign link to table patient actually matches up with the id in Illness. It also does the reverve, if a patient is deleted, it checks to make sure it is not referenced in illness. In order to do this effiently it needs to index these fields, otherwise it will have to do a spend too much time doing full table lookups.

Besides, the word key is a synonym for index so it makes sense to index keys :-).

Johan
  • 74,508
  • 24
  • 191
  • 319