# Topic 26: Primary Key
Row uniqueness, NOT NULL enforcement, candidate keys, surrogate vs natural keys, and clustered index implications.
1. Definition
A Primary Key (PK) is a column (or minimal set of columns) that uniquely identifies each row in a table. It strictly enforces uniqueness and forbids NULL values.
2. Explain Like I'm 5
A Primary Key is like your Citizen National ID or Passport Number: no two citizens can share the same number, and everyone is required to have one.
3. Animation & Visual Simulation
Interactive Engine TracePrimary Key Visual Simulator
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INT NOT NULL
);Active InputStep 1: Input & Parsing Stage
Initiating Primary Key
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
An employee directory where every employee is identified by a unique auto-incrementing ID.
| id (PK) | name | |
|---|---|---|
| 1 | lucky@company.com | Lucky |
| 2 | rahul@company.com | Rahul |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectCREATE TABLE users ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE );
CREATE TABLE student_courses ( student_id INT REFERENCES students(id), course_id INT REFERENCES courses(id), enrolled_at DATE NOT NULL DEFAULT CURRENT_DATE, PRIMARY KEY (student_id, course_id) );
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Uniqueness Invariant | No two rows can have the same primary key value. |
| NOT NULL Required | Primary key columns cannot contain NULL values. |
| One PK Per Table | A table can have exactly one primary key constraint (though it may span multiple columns). |
| Clustered vs Non-clustered primary key | MySQL InnoDB physically orders heap rows inside the PK B-Tree; PostgreSQL uses non-clustered heap tables. |
| UUID page split hazard | Random UUIDv4 primary keys cause catastrophic B-Tree page splits; use ordered UUIDv7 or BIGINT. |
7. Deep Dive: Surrogate Keys vs Natural Keys
A Natural Key is real-world data that is unique (like an email address or SSN). A Surrogate Key is an artificial system-generated identifier (like BIGINT IDENTITY or UUIDv7). Surrogate keys insulate database schemas from business identity changes (e.g. a user changing their email address).
-- Preferred Surrogate Key pattern: CREATE TABLE customers ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- Surrogate tax_id VARCHAR(50) UNIQUE NOT NULL -- Natural candidate );
8. Advantages & Disadvantages
Advantages
- •Guarantees entity integrity and row identification.
- •Automatically creates a high-performance unique B-Tree index.
Disadvantages & Trade-offs
- •Composite primary keys with wide text columns consume excessive index space.
9. Common Interview Questions
Q1.What is the architectural difference between a Surrogate Key and a Natural Key?
A Natural Key is an existing attribute with real-world business meaning (e.g. SSN, VIN, email). A Surrogate Key is a meaningless system-generated identifier (e.g. auto-increment BIGINT or UUID). Natural keys can change due to business pivots, causing massive cascading foreign key update overhead. Surrogate keys are immutable, compact, and decouple internal relations from external business logic.
Q2.Why are random UUIDv4 primary keys dangerous for write-heavy relational databases?
UUIDv4 values are completely random. When new rows are inserted into a B-Tree primary key index, random keys insert into random leaf pages across disk. As tables grow larger than RAM, every insert causes a random disk I/O and triggers B-Tree page splits (splitting 8 KB pages in half, causing 50% storage fragmentation). Using time-ordered UUIDv7 or sequential BIGINT ensures append-only sequential writes to the rightmost leaf page.
Q3.What is the physical difference between a Primary Key in PostgreSQL vs MySQL (InnoDB)?
In MySQL InnoDB, the table IS the primary key (Clustered Index): heap rows are stored directly in the leaf pages of the primary key B+ Tree. In PostgreSQL, all tables are unordered heaps: the primary key is just an ordinary unique B-Tree index whose leaf nodes point to 6-byte physical disk tuple locations (CTID) in the separate heap file.
Q4.Can a Primary Key consist of multiple columns (Composite Primary Key)?
Yes. A Composite Primary Key combines multiple columns to enforce row uniqueness: PRIMARY KEY (order_id, item_id). Under the hood, the engine creates a composite B-Tree index on the combined columns. The Leftmost Prefix Rule applies: queries filtering on order_id use the index, but queries filtering on item_id alone cannot navigate the tree without a full scan.
Q5.Can a table exist without a Primary Key in relational databases?
Technically yes: SQL allows creating heap tables without a primary key. However, it is an extreme antipattern in production: 1. You cannot uniquely identify or update specific rows, 2. Logical replication tools (like Debezium or AWS DMS) fail without a replica identity key, 3. Foreign key referential integrity cannot reference the table.
10. Interview-Ready Answer
“A Primary Key uniquely identifies rows in a table while enforcing NOT NULL. Best practice uses synthetic surrogate keys (such as BIGINT identity or sequential UUIDs) to protect foreign key relationships from mutable business attributes.”
11. Quick Test
Which of the following is TRUE about Primary Keys in SQL?