I am trying to understand the syntaxes for defining tables and I noticed that the column definitions include an option to indiciate that the column references a column from another table.
If I can already define this here, do I still need to explicitly define a FOREIGN KEY constraint specifying that column again? Why?
Because I imagine the REFERENCE definition added as a column constraint should already take care of the fact that the column is a foreign key (since it is referencing another table).
Example code for clarity:
a)
create table SAMPLE (
sample_id INT PRIMARY KEY,
client_id INT REFERENCES CLIENT (client_id)
);
b)
create table SAMPLE (
sample_id INT PRIMARY KEY,
client_id INT NOT NULL,
CONSTRAINT fk_sample_client
FOREIGN KEY (client_id) REFERENCES CLIENT (client_id)
);
Does definition (a) ensure that the clientId is identified as the foreign key, the same way definition (b) does?
2
Answers
As Simon shared , inline REFERENCES in column definitions are ignored by mySQL and this link gives further explanation as to why.
Simply put, the syntax will still only create the column; it will not specify it as a foreign key or carry out any checks on it.
REFERENCES as part of the column definition is ignored.
Source: https://dev.mysql.com/doc/refman/8.0/en/create-table.html