SQL Getting Sta...login
SQL Getting Started Tutorial Manual
author:php.cn  update time:2022-04-12 14:15:40

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:

CREATE TABLE Persons
(
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:

CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255) ,
Address varchar(255),
City varchar(255)
)
If you need to name the PRIMARY KEY constraint and define the PRIMARY KEY constraint for multiple columns, please use The following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

CREATE TABLE Persons
(
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 TABLE

When 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:

ALTER TABLE Persons
ADD PRIMARY KEY (P_Id)
To name a PRIMARY KEY constraint and define PRIMARY KEY constraints for multiple columns, please use the following SQL syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

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 constraint

To revoke PRIMARY KEY constraint, please use the following SQL:

MySQL:

ALTER TABLE Persons
DROP PRIMARY KEY

SQL Server / Oracle / MS Access:

ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID