0% found this document useful (0 votes)
2 views2 pages

Primary and Foreign Keys

Uploaded by

bob.ilukhor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Primary and Foreign Keys

Uploaded by

bob.ilukhor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Lecturer : Damien Kettle Module : Database Administration

Tutorial – Primary and Foreign Keys

Primary Keys
The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values.

Each table should have a primary key, and each table can have only ONE primary key.

SQL PRIMARY KEY Constraint on CREATE TABLE


The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons" table is created:

CREATE TABLE Persons


(
P_Id int NOT NULL PRIMARY KEY,
LastName nvarchar(255) NOT NULL,
FirstName nvarchar(255),
Address nvarchar(255),
City narchar(255)
)

SQL PRIMARY KEY Constraint on ALTER TABLE


To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the
following SQL:

ALTER TABLE Persons


ADD PRIMARY KEY (P_Id)

Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created).
Lecturer : Damien Kettle Module : Database Administration

Foreign Keys
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:

The "Orders" table:

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

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

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

SQL FOREIGN KEY on CREATE TABLE


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

You might also like