SQL PRIMARY KEY
A primary key uniquely identifies each row of a table. Every well-designed table has one.
Single-column primary key
SQL
CREATE TABLE customers ( id INT PRIMARY KEY, name VARCHAR(80) );
Composite primary key
Useful for pure join tables — no surrogate ID needed:
SQL
CREATE TABLE memberships ( user_id INT, team_id INT, PRIMARY KEY (user_id, team_id) );
Surrogate vs natural
| Type | Means | Trade-off |
|---|---|---|
| Surrogate | Auto-generated INT/BIGINT/UUID | Stable, never collides — but meaningless to humans. |
| Natural | A real-world value (SKU, email) | Self-descriptive — but changes hurt (cascades, FKs). |
Modern apps almost always use surrogate keys, with a separate UNIQUE on the natural key.
Auto-increment
SQL
-- MySQL CREATE TABLE t (id INT PRIMARY KEY AUTO_INCREMENT, ...); -- PostgreSQL CREATE TABLE t (id BIGSERIAL PRIMARY KEY, ...); -- legacy CREATE TABLE t (id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, ...); -- standard SQL -- SQL Server CREATE TABLE t (id INT PRIMARY KEY IDENTITY(1,1), ...);
UUID as primary key?
Use UUID when IDs need to be generated client-side, or when you don't want to leak row counts. Trade-off: bigger storage, slower B-tree inserts than sequential integers.
Tip: Always pick
BIGINT over INT for new primary keys. The extra storage is trivial; running out of INT range at 2.1 billion rows is not.Example
Exercise
Modern preferred integer type for new primary keys.
id
PRIMARY KEY
Six letters; bigger than INT.
Discussion
Loading…