SQL PRIMARY KEY Constraint

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.

Most tables 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 "C_Id" column when the "Employee" table is created:

SQL Server / Oracle / MS Access:

CREATE TABLE Customer
(
C_Idint NOT NULL PRIMARY KEY,
LastName varchar(100) NOT NULL,
FirstName varchar(100),
Address varchar(100),
City varchar(100)
);

MySQL:

CREATE TABLE Customer ( C_Idint NOT NULL,
LastName varchar(100) NOT NULL,
FirstName varchar(100),
Address varchar(100),
City varchar(100),
PRIMARY KEY (C_Id)
);

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

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Customer ( C_Idint NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT PK_CID PRIMARY KEY (C_Id,LastName)
);

Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the VALUE of the primary key is made up of TWO COLUMNS (P_Id + LastName).

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:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Customer ADD PRIMARY KEY (C_Id)

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

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Customer
ADD CONSTRAINT PK_CID PRIMARY KEY (C_Id,LastName)

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).

To DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

SQL Server / Oracle / MS Access:

ALTER TABLE Customer
DROP CONSTRAINT PK_CID

MySQL:

ALTER TABLE Customer
DROP PRIMARY KEY



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved