Document directory
- SQL Server:
- For MySQL/SQL Server/Oracle/MS access:
- For MySQL/SQL Server/Oracle/MS access:
- MySQL:
- SQL Server/Oracle/MS access:
SQL primary key constraints
The primary key constraint uniquely identifies each record in the database table.
The primary key must contain a unique value.
The primary key column cannot contain null values.
Each table should have a primary key, and each table can have only one primary key.
SQL Server:
CREATE TABLE Persons(Id_P int NOT NULL PRIMARY KEY
,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255))
To name the primary key constraint and define the primary key constraint for multiple columns, use the following SQL Syntax:
CREATE TABLE Persons(Id_P int NOT NULL,LastName varchar(255) NOT NULL,FirstName varchar(255),Address varchar(255),City varchar(255),CONSTRAINT uc_PersonID PRIMARY KEY (Id_P,LastName)
)
SQL primary key constraint on ALTER TABLE
If you create a primary key constraint for the "id_p" column when the table already exists, use the following SQL statement:
For MySQL/SQL Server/Oracle/MS access:
ALTER TABLE PersonsADD PRIMARY KEY (Id_P)
To name the primary key constraint and define the primary key constraint for multiple columns, use the following SQL Syntax:
For MySQL/SQL Server/Oracle/MS access:
ALTER TABLE PersonsADD CONSTRAINT pk_PersonID PRIMARY KEY (Id_P,LastName)
Note: If you use the alter table statement to add a primary key, you must declare that the primary key column does not contain null.
Value (when the table is created for the first time ).
Revoke the primary key constraint
To revoke the primary key constraint, use the following SQL statement:
MySQL:
ALTER TABLE PersonsDROP PRIMARY KEY
SQL Server/Oracle/MS access:
ALTER TABLE PersonsDROP CONSTRAINT pk_PersonID