In mysql foreign keys are defined 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]
Why do we need CONSTRAINT and symbol? It seems like there is index_name anyway - so I totally don't get the reason for CONSTRAINT keyword. Can someone clarify what it's for?
A foreign key joins a table to another table by referencing its primary key. A foreign key constraint specifies that the key can only contain values that are in the referenced primary key, and thus ensures the referential integrity of data that is joined on the two keys.
an index on a table is a data structure that makes random access to the rows fast and efficient. It helps to optimize the internal organization of a table as well. A foreign key is simply a pointer to a corresponding column in another table that forms a referential constraint between the two tables.
Foreign keys attributes are indicated by the notation (FK) beside them.
CONSTRAINT is the key word that tells MySQL that you wish to add a constraint. [symbol] is an optional name for the constraint. You can name it whatever you like. If you omit the name, MySQL will generate a name on its own, internally.
CONSTRAINT
is the key word that tells MySQL that you wish to add a constraint. [symbol]
is an optional name for the constraint. You can name it whatever you like. If you omit the name, MySQL will generate a name on its own, internally.
It's good to use the fk
prefix like fk_something
.
You'll need that symbol name when dropping the constraint:
ALTER TABLE tbl_name DROP FOREIGN KEY fk_something;
You can get the symbol name using SHOW CREATE TABLE
:
SHOW CREATE TABLE tbl_name;
You can't use an index name to refer to a constraint. Any index that may be added when you issue the CONSTRAINT
clause may be automatically removed later (e.g. if an index is explicitly added that will serve in its place).
All of this is answered in more detail in the MySQL Documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With