Solembum
Solembum

Reputation: 47

MySQL: does it matter to give names to the foreign keys?

Tell me please either should I to give name the foreign key?

CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action

I can do some manipulations with the constraint by it's name, but what I can do with the foreign key name? Give me some examples please.

Upvotes: 2

Views: 1806

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269493

As the documentation explains:

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 other words, what you are providing is not a "foreign key name" but a "(foreign key) index name".

Having a name for an index is useful for tracking that index.

To be honest, though, I don't provide such names. I would much rather explicitly declare an index on the foreign keys, rather than have the database do it for me.

(Note: Most databases do not automatically create an index when a foreign key is declared.)

Upvotes: 1

Sagar Gangwal
Sagar Gangwal

Reputation: 7937

Yes it is.

If you want to alter or drop constraint in future,then it is possible using name only.

DROP FOREIGN KEY constraint_name;

You can check here.

Upvotes: 2

Related Questions