Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraint symbol vs foreign key index name -> what's the difference?

Tags:

mysql

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?

like image 706
Dannyboy Avatar asked Dec 09 '13 15:12

Dannyboy


People also ask

What is the difference between foreign key and foreign key constraint?

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.

What is the difference between foreign key and index?

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.

What is the symbol of foreign key?

Foreign keys attributes are indicated by the notation (FK) beside them.

What is constraint symbol in MySQL?

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.


1 Answers

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.

like image 167
Marcus Adams Avatar answered Oct 06 '22 15:10

Marcus Adams