W
W
Webber2021-03-05 10:24:51
MySQL
Webber, 2021-03-05 10:24:51

Is index required for foreign key?

In the mysql doc, the index on fk is mandatory and auto-created, this is indicated in the doc:

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.


In postgres, sqlite checked auto index is not created.

Is this a feature of mysql or a "rule of good manners" to create an index in all databases?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton_habr_2020, 2021-03-05
@Anton_habr_2020

In MySQL, the index creates the same MySQLWorkbench when the ForeingKey is created, however you can delete it manually or create the FK with a script without creating the index. So the index is not required.
However, when you change related records, the database will try to apply the FK settings for your table and change the related records or reset them. And when deleting, check whether it is possible to delete.
If there is a lot of data in the table, then without an index, these operations will take a long time.

G
galaxy, 2021-03-05
@galaxy

postgres :

The foreign key must refer to the columns that form the primary key or unique constraint. In this way, there will always be an index on the related columns (defined by the corresponding primary key or constraint), which means that checks against the related row will be performed efficiently.

You need UNIQUE CONSTRAINT on the parent table, otherwise how can you understand, generally speaking, which record the foreign key on the child refers to?
De facto, uniqueness constraints are implemented everywhere through indexes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question