The PRIMARY KEY constraint ensures each record in a table is uniquely identified. A table can have only one primary key, which may consist of either a single field or multiple fields.
The subsequent SQL establishes a PRIMARY KEY on the “ID” column during the creation of the “Persons” table:
MySQL:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, PRIMARY KEY (ID) ); |
SQL Server / Oracle / MS Access:
CREATE TABLE Persons ( ID int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int ); |
To enable naming of a PRIMARY KEY constraint and to define a PRIMARY KEY constraint on multiple columns, utilize the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int, CONSTRAINT PK_Person PRIMARY KEY (ID,LastName) ); |
Note: In the example provided, there is only ONE PRIMARY KEY (PK_Person). However, the VALUE of the primary key is composed of TWO COLUMNS (ID + LastName).
To add a PRIMARY KEY constraint on the “ID” column after the table is already created, employ the following SQL:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD PRIMARY KEY (ID); |
For naming a PRIMARY KEY constraint and defining it on multiple columns, utilize the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName); |
Note: If you employ the ALTER TABLE statement to add a primary key, the primary key column(s) must have been initially declared to not contain NULL values when the table was first created.
To remove a PRIMARY KEY constraint, employ the following SQL:
MySQL:
ALTER TABLE Persons DROP PRIMARY KEY; |
SQL Server / Oracle / MS Access:
ALTER TABLE Persons DROP CONSTRAINT PK_Person; |