From the course: MySQL Advanced Topics (2019)

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Creating foreign key constraints

Creating foreign key constraints - MySQL Tutorial

From the course: MySQL Advanced Topics (2019)

Creating foreign key constraints

- [Narrator] A foreign key constraint is generally added as part of the CREATE TABLE statement. Here I have copied from the Chapter Six exercise files. We're using the scratch database, and we're creating a couple of tables, widgetCustomer and widgetSale, and in the widgetSale table I've specified a foreign key constraint. You'll notice the CONSTRAINT key word here. The CONSTRAINT keyword is optional, but it allows us to name the constraint. This is valuable, and we'll use it later. In this case, I've named the constraint custid for customer_id. A foreign key requires an index. If you don't create one explicitly the system will create one for you. And the foreign key itself is specified with the FOREIGN KEY keyword, and an index name and column name in this form. We have here custid for the index name and customer_id as the column name, just as we did when we defined the index. The REFERENCES clause specifies the…

Contents