In MySQL, with FKs, what does "CONSTRAINT" do?

I looked through MySQL 5.1 docs and still can’t understand that I noticed the difference between the code I entered in MySQL and the system output code.

What is the difference between sample code 01 and 02, i.e. 02 added CONSTRAINT to FOREIGN KEY - why and what does it do?

CODE_SAMPLE_01:

 FOREIGN KEY (TABLE_02_nID_FK__TABLE_01_sID_PK) REFERENCES TABLE_01(TABLE_01_sID_PK), 

CONTEXT:

 CREATE TABLE `TABLE_02` ( `TABLE_02_sID_PK` int(8) NOT NULL, `TABLE_02_nID_FK__TABLE_01_sID_PK` int(8) NOT NULL, `TABLE_02_cID` int(8) NOT NULL, `TABLE_02_data01` varchar(128) default NULL, `TABLE_02_data02` varchar(128) NOT NULL, `create_timestamp` DATETIME DEFAULT NULL, `update_timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`TABLE_02_sID_PK`), FOREIGN KEY (TABLE_02_nID_FK__TABLE_01_sID_PK) REFERENCES TABLE_01(TABLE_01_sID_PK), INDEX `TABLE_02_nID_FK__TABLE_01_sID_PK` (`TABLE_02_nID_FK__TABLE_01_sID_PK`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

CODE_SAMPLE_02:

 CONSTRAINT `table_02_ibfk_1` FOREIGN KEY (`TABLE_02_nID_FK__TABLE_01_sID_PK`) REFERENCES `table_01` (`TABLE_01_sID_PK`) 

CONTEXT:

 CREATE TABLE `table_02` ( `TABLE_02_sID_PK` int(8) NOT NULL, `TABLE_02_nID_FK__TABLE_01_sID_PK` int(8) NOT NULL, `TABLE_02_cID` int(8) NOT NULL, `TABLE_02_data01` varchar(128) DEFAULT NULL, `TABLE_02_data02` varchar(128) NOT NULL, `create_timestamp` datetime DEFAULT NULL, `update_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`TABLE_02_sID_PK`), KEY `TABLE_02_nID_FK__TABLE_01_sID_PK` (`TABLE_02_nID_FK__TABLE_01_sID_PK`), CONSTRAINT `table_02_ibfk_1` FOREIGN KEY (`TABLE_02_nID_FK__TABLE_01_sID_PK`) REFERENCES `table_01` (`TABLE_01_sID_PK`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 
+6
mysql ddl referential-integrity
source share
1 answer

The optional CONSTRAINT keyword allows you to specify a name for the foreign key. Without it, a name is automatically generated.

This name can be seen in the INFORMATION_SCHEMA TABLE_CONSTRAINTS table.

+9
source share

All Articles