bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/SQL/SQL Database
SQL•SQL Database

SQL FOREIGN KEY Constraint

Concept visual

SQL FOREIGN KEY Constraint

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

Overview

The FOREIGN KEY

constraint establishes a link between two tables, and prevents action that will destroy the link between them.

A Foreign Key

is a column in a table that refers to the PRIMARY KEY in another table. The table with the foreign key column is called the child table, and the table with the primary key column is called the referenced or parent table.

The FOREIGN KEY

constraint prevents invalid data from being inserted into the foreign key column (in the child table), because the value has to exist in the parent table.

The FOREIGN KEY

constraint also prevents you from deleting a record in the parent table, if related rows still exist in the child table.

Assume we have two tables:

Persons Table

PersonID

LastName

FirstName

Age

Hansen

Ola

30

Svendson

Tove

23

Orders Table

OrderID

OrderNumber

PersonID

22456

24562

Here we see that the "PersonID" column in the "Orders" table points to the "PersonID" column in the "Persons" table. The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "PersonID" column in the "Orders" table is the FOREIGN KEY in the "Orders" table.

FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY

constraint on the "PersonID" column upon creation of the "Orders" table:

CREATE TABLE Orders

( OrderID int PRIMARY KEY, OrderNumber int NOT NULL, PersonID int, CONSTRAINT fk_Person FOREIGN KEY (PersonID)

REFERENCES Persons(PersonID)

);

FOREIGN KEY on ALTER TABLE

Previous

SQL PRIMARY KEY Constraint

Next

SQL CHECK Constraint