Loading lesson path
Concept visual
Start at both ends
❮ SQL Keywords
constraint is a key used to link two tables together. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created:
( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);Formula
SQL Server / Oracle / MS Access:( OrderID int NOT NULL PRIMARY KEY, OrderNumber int NOT NULL,
);To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
Formula
MySQL / SQL Server / Oracle / MS Access:( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
);To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is already created, use the following SQL:
Formula
MySQL / SQL Server / Oracle / MS Access:ADD FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID);To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
Formula
MySQL / SQL Server / Oracle / MS Access:ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID);To drop a FOREIGN KEY constraint, use the following SQL:
DROP FOREIGN KEY FK_PersonOrder;Formula
SQL Server / Oracle / MS Access:DROP CONSTRAINT FK_PersonOrder;❮ SQL Keywords