Skip to content
Back to 50 Concepts
Topic 26 of 50foundationsBeginner

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

Primary Key Visual Simulator

Step 1 of 3
SQL>CREATE TABLE orders ( id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, customer_id INT NOT NULL );Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for Primary Key
SQL Input

Initiating Primary Key

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Passport Number: Uniquely identifies you worldwide and can never be empty.

4. Real-World Example

An employee directory where every employee is identified by a unique auto-incrementing ID.

Employees Table
id (PK)emailname
1lucky@company.comLucky
2rahul@company.comRahul
Relational walkthrough: The primary key guarantees that employee #1 is completely unique across the entire organization.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Single-column Identity Primary Key
CREATE TABLE users (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email VARCHAR(255) NOT NULL UNIQUE
);
Automatically creates a unique B-Tree index on id.
Step 2: Composite Primary Key for Junction Tables
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)
);
Ensures a student cannot enroll in the exact same course twice.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Uniqueness InvariantNo two rows can have the same primary key value.
NOT NULL RequiredPrimary key columns cannot contain NULL values.
One PK Per TableA table can have exactly one primary key constraint (though it may span multiple columns).
Clustered vs Non-clustered primary keyMySQL InnoDB physically orders heap rows inside the PK B-Tree; PostgreSQL uses non-clustered heap tables.
UUID page split hazardRandom 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
);
Caution: Using mutable natural keys (like email) as primary keys causes painful foreign key cascades when values change.

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

Scenario Question:

Which of the following is TRUE about Primary Keys in SQL?

Select your answer: