Receive all updates via Facebook. Just Click the Like Button Below

Blogger Widgets
/

Watch Intro About My Website ! ! !

Monday, 4 November 2013

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Let's illustrate the foreign key with an example. Look at the following two tables:

The "Persons" table:

Id
LastName
FirstName
Address
City
1
Navis
Anto
Madras
TVL
2
Ji
Bala
Bombay
TVL
3
Christopher
Franklin
America
KK

The "Orders" table:

Id
OrderNo
Id
1
77895
3
2
44678
3
3
22456
2
4
24562
1

Note that the "Id" column in the "Orders" table points to the "Id" column in the "Persons" table.

The "Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

The FOREIGN KEY constraint also prevents that invalid data form being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.

SQL FOREIGN KEY Constraint on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "Id" column when the "Orders" table is created:

MySQL:

CREATE TABLE Orders
(
Id int NOT NULL,
OrderNo int NOT NULL,
Id int,
PRIMARY KEY (Id),
FOREIGN KEY (Id) REFERENCES Persons(Id)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Orders
(
Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
Id int FOREIGN KEY REFERENCES Persons(Id)
)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Orders
(
Id int NOT NULL,
OrderNo int NOT NULL,
Id int,
PRIMARY KEY (Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (Id)
REFERENCES Persons(Id)
)

SQL FOREIGN KEY Constraint on ALTER TABLE
To create a FOREIGN KEY constraint on the "Id" column when the "Orders" table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD FOREIGN KEY (Id)
REFERENCES Persons(Id)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (Id)
REFERENCES Persons(Id)

To DROP a FOREIGN KEY Constraint
To drop a FOREIGN KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders

SQL Server / Oracle / MS Access:

ALTER TABLE Orders
DROP CONSTRAINT fk_PerOrders


Tagged:

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...