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?
As documented under
FOREIGN KEYConstraints: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 namednamewith an automatically generated index name (if one does not already exist).Other than that, they are identical.