Limeni
Limeni

Reputation: 5224

MySQL Foreign key definition?

I'm playing around with mysql and I found two ways to define Foreign keys:

CREATE TABLE posts(
    id INT NOT NULL AUTO_INCREMENT,
    user_id INT NOT NULL,
    post_title VARCHAR(255) NOT NULL,
    PRIMARY KEY(id),
    FOREIGN KEY name (user_id) REFERENCES users(id)
);

And:

CREATE TABLE posts(
    id INT NOT NULL AUTO_INCREMENT,
    user_id INT NOT NULL,
    post_title VARCHAR(255) NOT NULL,
    PRIMARY KEY(id),
    CONSTRAINT name
        FOREIGN KEY(user_id) 
        REFERENCES users(id)
);

What would be the difference between these two? Are they the same and its just a matter of preference how you like to write? Or there are some differences?

Upvotes: 2

Views: 1296

Answers (1)

eggyal
eggyal

Reputation: 125835

As documented under FOREIGN KEY Constraints:

The syntax for an InnoDB foreign key constraint definition in the CREATE TABLE or ALTER TABLE statement looks like this:

[CONSTRAINT [symbol]] FOREIGN KEY
    [index_name] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name,...)
    [ON DELETE reference_option]
    [ON UPDATE reference_option]

reference_option:
    RESTRICT | CASCADE | SET NULL | NO ACTION

index_name represents a foreign key ID. If given, this is ignored if an index for the foreign key is defined explicitly. Otherwise, if InnoDB creates an index for the foreign key, it uses index_name for the index name.

Foreign keys definitions are subject to the following conditions:

[ deletia ]

  • If the CONSTRAINT symbol clause is given, the symbol value must be unique in the database. If the clause is not given, InnoDB creates the name automatically.

[ deletia ]

If the FOREIGN KEY clause included a CONSTRAINT name when you created the foreign key, you can refer to that name to drop the foreign key. Otherwise, the fk_symbol value is internally generated by InnoDB when the foreign key is created.

Therefore, your first example creates an automatically named foreign key constraint with an index named name (if one does not already exist); whereas your second example creates a foreign key constraint named name with an automatically generated index name (if one does not already exist).

Other than that, they are identical.

Upvotes: 2

Related Questions