Curriculum
Course: SQL
Login

Curriculum

SQL

SQL References

0/80

MySQL Functions

0/139

SQL Server Functions

0/84

SQL Quick Ref

0/1
Text lesson

PRIMARY KEY

PRIMARY KEY

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.

SQL PRIMARY KEY on CREATE TABLE

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).

SQL PRIMARY KEY on ALTER TABLE

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.

DROP a PRIMARY KEY Constraint

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;