Skip to content

SQL PRIMARY KEY Constraint

A primary key is the column, or set of columns, that identifies each row of a table. Its values must be unique and can never be empty, and a table has exactly one primary key. Other tables refer to a row by its primary key, as each invoice refers to its production by ProductionID.

In the example database, each production is identified by its ProductionID:

CREATE TABLE Productions (
ProductionID int PRIMARY KEY,
Title varchar(200) NOT NULL,
Format varchar(50) NOT NULL
);

A second production with ID 1 is refused, as is a production with no ID at all.

A primary key is best kept to a value with no meaning of its own, such as a number the database hands out. A title can change or be shared by two productions; an ID never needs to. SQL Auto Increment shows how to have the database number rows for you.

Sometimes no single column is unique, but a combination is. A table recording which crew member works on which production holds each pairing once, while the same person can join several productions and a production has many people:

CREATE TABLE CrewAssignments (
CrewID int,
ProductionID int,
StartDate date,
CONSTRAINT PK_CrewAssignment PRIMARY KEY (CrewID, ProductionID)
);

Crew member 2 can be assigned to productions 1 and 2, but a second assignment of crew member 2 to production 1 is refused. There is still only one primary key; it simply spans two columns.

ALTER TABLE Productions
ADD CONSTRAINT PK_Productions PRIMARY KEY (ProductionID);

The key columns must already hold no NULLs and no repeats. To remove the key, drop it by name with ALTER TABLE Productions DROP CONSTRAINT PK_Productions;, or in MySQL with ALTER TABLE Productions DROP PRIMARY KEY;.