Pages - Menu

Tuesday, 3 January 2012

Primary Key


A primary key is used to uniquely identify each row in a table. It can either be part of the actual record itself , or it can be an artificial field (one that has nothing to do with the actual record). A primary key can consist of one or more fields on a table. When multiple fields are used as a primary key, they are called a composite key.

Primary keys can be specified either when the table is created (using CREATE TABLE) or by changing the existing table structure (using ALTER TABLE).

Below are examples for specifying a primary key when creating a table


MySQL:
CREATE TABLE Employee
(ID integer,
Last_Name varchar(30),
First_Name varchar(30),
PRIMARY KEY (ID));

Oracle:
CREATE TABLE Employee
(ID integer PRIMARY KEY,
Last_Name varchar(30),
First_Name varchar(30));

SQL Server:
CREATE TABLE Employee
(ID integer PRIMARY KEY,
Last_Name varchar(30),
First_Name varchar(30));

Below are examples for specifying a primary key by altering a table:

MySQL:
ALTER TABLE Employee ADD PRIMARY KEY (ID);

Oracle:
ALTER TABLE Employee ADD PRIMARY KEY (ID);

SQL Server:
ALTER TABLE Employee ADD PRIMARY KEY (ID);

Note: Before using the ALTER TABLE command to add a primary key, you'll need to make sure that the field is defined as 'NOT NULL' -- in other words, NULL cannot be an accepted value for that field.

No comments:

Post a Comment