Home SQL Foreign Key
E-mail Print PDF

FOREIGN KEY - One table points to another PRIMARY KEY.

Look at the following two tables:

There is a table "Persons":

P_IdLastNameFirstNameAddressCity
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

O_IdOrderNoP_Id
1 77895 3
2 44678 3
3 22456 2
4 24562 1

The column "P_Id" in table "Orders" is a FOREIGN KEY.

SQL FOREIGN KEY constraints in CREATE TABLE

MySQL:

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

SQL Server / Oracle / MS Access:

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

MySQL / SQL Server / Oracle / MS Access:

1
2
3
4
5
6
7
8
CREATE TABLE Orders(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)

SQL FOREIGN KEY constraints in ALTER TABLE

MySQL / SQL Server / Oracle / MS Access:

1
2
3
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

MySQL / SQL Server / Oracle / MS Access:

1
2
3
4
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

Removal of FOREIGN KEY

MySQL:

1
2
ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders

SQL Server / Oracle / MS Access:

1
2
ALTER TABLE Orders
DROP CONSTRAINT fk_PerOrders

Comments

 
+2 #1 Симо 2011-07-07 15:50 Very useful tutorial. Only now I realized what these are foreign keys. Quote
 
 
+3 #2 Sin 2011-08-14 17:32 Thanks for the lesson, only two voznyklo Question:
1
2 s?
Quote
 

Authorization

Nice Ajax Poll

Which one of my extensions is the best?

Statistics

Translate

русскийitalianoDeutschEnglishLATVIANукраїнськаfrançaispolski
1

Advertisement