In this tutorial, we will learn how to use FOREIGN KEY using SQL.
FOREIGN KEY constraint is used to link two tables together and it is also termed as a referencing key.FOREIGN KEY constraint is a field or collections of fields in one table that refers to the PRIMARY KEY constraint in another table.PRIMARY KEY is termed as parent table or referenced table, and a table containing the FOREIGN KEY is termed as the child table.Let us consider these two tables "Customer" and "Orders" for records.
Table Name: Customer
| CustID | CustName | City | Age |
| 1 | Tom Hardy | New York | 30 |
| 2 | Hugh Jackman | L.A. | 23 |
| 3 | Chris Pratt | Sydney | 20 |
Table Name: Orders
| OrderID | OrderNumber | CustID |
| 1 | 87855 | 3 |
| 2 | 85784 | 3 |
| 3 | 78585 | 2 |
| 4 | 24562 | 1 |
Here that column "CustID" in the table "Orders" points to the column "CustID" in the table "Customer".
Column "CustID" in the table "Customer" is the PRIMARY KEY in the table "Persons".
Column "CustID" in the table "Orders" is the FOREIGN KEY in the table "Orders".
FOREIGN KEY constraint prevents invalid data being inserted into the FOREIGN KEY column because it has to be one of the values contained in the table it points to.
A FOREIGN KEY constraint is also used to ensures that the links between tables would not be destroyed.
To add a FOREIGN KEY when the table is created, a statement is as follow:
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
CustID int FOREIGN KEY REFERENCES Customer(CustID)
);
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
CustID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (CustID) REFERENCES Persons(CustID)
);
To define a FOREIGN KEY constraint on multiple columns use this syntax, a statement is as follow:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
CustID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_CustmOrder FOREIGN KEY (CustID)
REFERENCES Customer(CustID)
);
To add FOREIGN KEY constraint after creating the table, a statement is as follow:
ALTER TABLE Orders
ADD FOREIGN KEY(CustID) REFERENCES Customer(CustID);
To add FOREIGN KEY constraint after creating the table on the multiple columns, a statement is as follow:
ALTER TABLE Orders
ADD CONSTRAINT FK_CustmOrder
FOREIGN KEY (CustID) REFERENCES Customer(CustID);
To drop a FOREIGN KEY constraint, a statement is as follow:
ALTER TABLE Orders
DROP CONSTRAINT FK_CustmOrder;
ALTER TABLE Orders
DROP FOREIGN KEY FK_CustmOrder;