Learn SQL
-- constraints.primary_key

PRIMARY KEY in SQL

Give every row a unique, permanent identity

--concept

A PRIMARY KEY is the column (or column pair) that identifies each row uniquely. The engine enforces two rules forever: values are never NULL and never duplicated. It also builds an index on the key automatically, so lookups by id are fast. Every well-designed table has one — order numbers, user ids, employee ids all exist because the primary key guarantees them.

--how it works
1

Declare the key

Inline (id INTEGER PRIMARY KEY) or as a table clause (PRIMARY KEY (id)) — both create the same constraint plus its supporting index.

2

Every INSERT is checked

The engine tests the new key value against the existing set before writing: duplicate or NULL means the whole statement fails with a constraint violation.

3

The index does double duty

The key’s B-tree keeps lookups by id at a handful of page reads regardless of table size — enforcement and speed from one structure.

4

Updates are checked too

Changing a key value re-runs the uniqueness test; most designs treat ids as immutable and never update them at all.

5

Composite keys span columns

PRIMARY KEY (student_id, course_id) makes the pair unique — either column alone may repeat, the combination may not.

--visualization
idnamesalary1Alice850002Bob520003Cynthia910004David470005Elena580006Farid73000employeesNEW ROWid = 1 · ZaraEngineering · 80000🔑pk index… checkingprobe runs before any write
result
Stage 1 / 4
The lesson example: INSERT (1, 'Zara', 'Engineering', 80000, 30) — but id 1 already belongs to Alice.
--example
query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (1, 'Zara', 'Engineering', 80000, 30);
Result
error
ERROR: duplicate key value violates unique constraint "employees_pkey"Detail: Key (id)=(1) already exists.

id 1 already belongs to Alice, so the engine refuses the insert with a constraint violation. The table is unchanged — that refusal is the whole point: an id can never quietly point at two people.

--variants

Unique id — accepted

A fresh key value sails through the check and lands in the table.

query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (7, 'Grace', 'Engineering', 81000, 31);
Result
idnamedepartmentsalaryage
7GraceEngineering8100031
1The engine probes the key index for id 7 — no entry exists.
2The row is written and the index gains one leaf.
3Result: 1 row inserted, and id 7 is now permanently taken.

Duplicate id — rejected

The second row with id 1 cannot exist; the engine refuses the statement.

query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (1, 'Zara', 'Engineering', 80000, 30);
Result
error
ERROR: duplicate key value violates unique constraint "employees_pkey"
1The index probe for id 1 finds Alice’s row already there.
2The statement aborts with a unique_violation — nothing partial is written.
3Two rows can never share an identity; every FK pointing at id 1 keeps a single unambiguous target.

NULL id — rejected

Identity requires a value; NULL means “unknown”, which cannot identify a row.

query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (NULL, 'Hugo', 'Sales', 49000, 27);
Result
error
ERROR: null value in column "id" violates not-null constraint
1PRIMARY KEY implies NOT NULL — the two rules are inseparable.
2The insert fails before any data page is touched.
3Use a generated/auto-increment key instead of inventing ids by hand.

Composite key pairs

Enrollment tables live on composite keys: the pair must be unique, the parts may repeat.

query.sql
1CREATE TABLE enrollments (
2 student_id INTEGER,
3 course_id INTEGER,
4 PRIMARY KEY (student_id, course_id)
5);
6-- (1, 100) ok · (1, 101) ok · (1, 100) again → duplicate
Result
pairresult
(1, 100)OK
(1, 101)OK
(1, 100)ERROR: duplicate key
1Student 1 may take many courses; course 100 may hold many students.
2Only the combination is constrained to be unique.
3This one table is the entire many-to-many relationship — with integrity built in.
--key facts
One per tablea table has exactly one primary key — but it may span several columns
Auto indexthe engine builds the supporting index for you; no extra CREATE INDEX needed
Surrogate vs naturalauto-increment ids (surrogate) are popular because business data changes — ids should not
--use cases
Every table’s identity column: users, orders, payments, employees
Idempotent imports: re-running a load is safe because duplicate keys are rejected
Composite junction tables: student×course, actor×film, tag×post
Debugging: when “the same row” appears twice, the first question is always “what is the key?”
--under the hood
The primary key index is usually the table’s clustered base in MySQL/SQL Server — row data itself lives in key order there.
Auto-increment (serial/identity) keys insert monotonically, appending at the index’s right edge; random keys (UUID v4) scatter inserts across the tree and fragment it.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.