Mark As Completed Discussion

FOREIGN KEY Constraint

A foreign key is a field in a table that uniquely identifies each row of another table. A column (or set of columns) in one table that is the FOREIGN KEY relates to the PRIMARY KEY of another table. The table with the FOREIGN KEY is referred to as the child table, and the table with the PRIMARY KEY is referred to as the parent table. The FOREIGN KEY constraint may be specified either at the time the table is created or may be added later via an alter statement. Imagine we have a Customer table created with the constraints explained in the examples above, and another table called Orders, which keeps track of every order that has been made. These tables can be seen below:

FOREIGN KEY Constraint
The Customer_Id is the PRIMARY KEY in the Customer Table. However, the Customer_Id is a FOREIGN KEY in the Orders Table. In order to create the Orders table, we run the following SQL query:

TEXT/X-SQL
1CREATE TABLE Orders (
2    Order_Id int NOT NULL UNIQUE,
3    PRIMARY KEY (Order_Id),
4    FOREIGN KEY (Customer_Id) REFERENCES Customer(Customer_Id)
5);

In order to create a FOREIGN KEY in an already created table, use the following syntax:

TEXT/X-SQL
1ALTER TABLE Customer (
2ADD FOREIGN KEY (Customer_Id) REFERENCES Customer(Customer_Id);
3);