SQL PRIMARY KEY
SQL PRIMARY KEY Constraints
PRIMARY KEY constraints uniquely identify each record in a database table.
The primary key must contain a unique value.
Primary key columns cannot contain NULL values.
Each table should have a primary key, and each table can only have one primary key.
SQL PRIMARY KEY constraint when CREATE TABLE
The following SQL creates a PRIMARY KEY constraint on the "P_Id" column when the "Persons" table is created:
MySQL:
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255 ),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
##SQL Server / Oracle / MS Access:
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255) ,
Address varchar(255),
City varchar(255)
)
MySQL / SQL Server / Oracle / MS Access:
P_Id int NOT NULL ,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName )
)
Note: In the above example, there is only one primary key PRIMARY KEY (pk_PersonID). However, the value of pk_PersonID is represented by two columns (P_Id and
LastName).
SQL PRIMARY KEY constraint when ALTER TABLEWhen the table has been created, if you need to create a PRIMARY KEY constraint on the "P_Id" column, please use the following SQL :
MySQL/SQL Server/Oracle/MS Access:
MySQL / SQL Server / Oracle / MS Access:
Note: If you use the ALTER TABLE statement to add a primary key, The primary key column must be declared as not containing NULL values (when the table is first created).
Revoke PRIMARY KEY constraintTo revoke PRIMARY KEY constraint, please use the following SQL:
MySQL:
SQL Server / Oracle / MS Access: