From the course: MySQL Advanced Topics
Unlock this course with a free trial
Join today to access over 24,700 courses taught by industry experts.
Creating foreign key constraints - MySQL Tutorial
From the course: MySQL Advanced Topics
Creating foreign key constraints
- [Bill] Hi, I am Bill Weinman. A foreign key constraint is generally added as part of the CREATE TABLE statement. I've copied this block of SQL from the chapter six exercise file. Go ahead and use the scratch database for this, and I'm going to create a couple of tables, widgetSale and WidgetCustomer. Let's take a look at them first. widgetCustomer has just got a name and an id. widgetSale has id, item_id, customer_id, et cetera, quantity, price, and the constraint. So the constraint keyword is optional, but it allows us to name the constraint and this is valuable and we'll want to use it later. In this case, I've named the constraint custid. A foreign key constraint requires an index, and if you do not create one explicitly, the system will create it for you. I prefer to create it explicitly. And the foreign key constraint is specified with an index name, so here's the index name and a column name, here, customer_id. And it references the id column on the widgetCustomer table. So…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.