Careeroza
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 key | Surrogate key | |
|---|---|---|
| What | a real-world value (email, PAN number, ISBN) | a generated number or UUID with no meaning |
| Pros | meaningful, no extra column | never changes, small, fast joins |
| Cons | can change, can be long | needs 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.