iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

TypeMeansTrade-off
SurrogateAuto-generated INT/BIGINT/UUIDStable, never collides — but meaningless to humans.
NaturalA 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

Example
CREATE TABLE customers (
  id INT PRIMARY KEY,
  name VARCHAR(80)
);
Try it Yourself »

Exercise

Modern preferred integer type for new primary keys.

id PRIMARY KEY

Test yourself

Q1. A table can have…
Q2. For new schemas in 2026 most teams use…
Q3. A natural key disadvantage is…

Discussion

Loading…