Friday, 15 February 2013

What is the SQL PRIMARY KEY Constraint Syntax and Examples

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.


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 "C_Id" column when the "Customers" table is created:
MySQL:
CREATE TABLE Customers
(
C_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (C_Id)
)

SQL Server / Oracle / MS Access:

CREATE TABLE Customers
(
C_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

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 Customers
(
C_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_CustomerID PRIMARY KEY (C_Id,LastName)
)

Note: In the example above there is only ONE PRIMARY KEY (pk_CustomerID). However, the value of the pk_CustomerID is made up of two columns (C_Id and LastName).


SQL PRIMARY KEY Constraint on ALTER TABLE

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

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Customers
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 Customers
ADD CONSTRAINT pk_CustomerID 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


MYSQL:

ALTER TABLE Customers

DROP PRIMARY KEY
SQL Server / Oracle / MS Access:
ALTER TABLE Customers
DROP CONSTRAINT pk_CustomerID

No comments:

Post a Comment

Follow Me by Email

ExcelKingdom-Popular Posts

ExcelKingdom-Random Posts