What is a proper naming convention for MySQL FKs?

Viewed 69435

Being that they must be unique, what should I name FK's in a MySQL DB?

4 Answers

In MySQL, there is no need to give a symbolic name to foreign key constraints. If a name is not given, InnoDB creates a unique name automatically.

In any case, this is the convention that I use:

fk_[referencing table name]_[referenced table name]_[referencing field name]

Example:

CREATE TABLE users(
    user_id    int,
    name       varchar(100)
);

CREATE TABLE messages(
    message_id int,
    user_id    int
);

ALTER TABLE messages ADD CONSTRAINT fk_messages_users_user_id 
    FOREIGN KEY (user_id) REFERENCES users(user_id);

I try to stick with the same field names in referencing and referenced tables, as in user_id in the above example. When this is not practical, I also append the referenced field name to the foreign key name.

This naming convention allows me to "guess" the symbolic name just by looking at the table definitions, and in addition it also guarantees unique names.

fk-[referencing_table]-[referencing_field]

The reason is the combination of referencing_table and referencing_field is unique in a database. This way make the foreign key name easy to read, for example:

table `user`:
    id
    name
    role

table `article`:
    id
    content
    created_user_id /* --> user.id */
    reviewed_user_id /* --> user.id */

So we have two foreign keys:

fk-article-created_user_id
fk-article-reviewed_user_id

Adding user table name to foreign key name is reduntdant.

Related