PRIMARY KEY

SQL PRIMARY KEY Constraint

The PRIMARY KEY uniquely identifies each record in a table. It must contain UNIQUE values and cannot contain NULL. A table can have only one primary key, which may consist of one or several columns.

CREATE TABLE Persons (
    ID        INT NOT NULL,
    LastName  VARCHAR(255) NOT NULL,
    FirstName VARCHAR(255),
    PRIMARY KEY (ID)
);

Composite Primary Key

When no single column is unique, combine columns. In an order line table, the pair (OrderID, ProductID) identifies each row.

CREATE TABLE OrderLines (
    OrderID   INT,
    ProductID INT,
    Quantity  INT,
    CONSTRAINT PK_OrderLines PRIMARY KEY (OrderID, ProductID)
);

Add or Drop a Primary Key

ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID);

-- MySQL
ALTER TABLE Persons DROP PRIMARY KEY;
-- SQL Server / Oracle / PostgreSQL
ALTER TABLE Persons DROP CONSTRAINT PK_Person;

Natural vs Surrogate Keys

Natural keySurrogate key
Whata real-world value (email, PAN number, ISBN)a generated number or UUID with no meaning
Prosmeaningful, no extra columnnever changes, small, fast joins
Conscan change, can be longneeds an extra UNIQUE constraint on the natural value

Tip: Most applications use a surrogate key (auto-increment or UUID) as the primary key, plus a UNIQUE constraint on the natural key.