OwlTheEngineer
How It Actually WorksEpisode 54 · Backend

Primary key vs foreign key: the difference explained

Why primary keys uniquely identify single rows, and how foreign keys enforce referential integrity and build relationships across relational database tables.

Owl · 1 min read · 0 views
– comments
Ep 54 · Backend
60s VISUAL BREAKDOWN
Episode 54
Watch the fast visual breakdown or discuss on social:

In relational database systems (RDBMS) like PostgreSQL, MySQL, and SQLite, keys are the structural foundation that maintain data consistency and speed up queries.

The two most fundamental constraints are Primary Keys (PK) and Foreign Keys (FK).


1. What is a Primary Key (PK)?

A Primary Key is a column (or combination of columns) that uniquely identifies a specific row within its own table.

Table: users
┌───────────────┬─────────────────┬───────────────────────────┐
│ user_id (PK)  │ name            │ email                     │
├───────────────┼─────────────────┼───────────────────────────┤
│ 42            │ Alice Smith     │ alice@example.com         │
│ 43            │ Bob Jones       │ bob@example.com           │
└───────────────┴─────────────────┴───────────────────────────┘

The 3 Golden Rules of Primary Keys:

  1. Uniqueness: No two rows can ever share the same Primary Key value.
  2. Non-Null: A Primary Key value can never be NULL.
  3. Clustered Indexing: The database engine automatically builds a high-performance B-Tree index on the Primary Key, providing O(log N) point lookups in sub-milliseconds.

2. What is a Foreign Key (FK)?

A Foreign Key is a column in a child table that points to the Primary Key of a parent table.

Table: orders
┌───────────────┬─────────────────┬───────────┬───────────────────────┐
│ order_id (PK) │ user_id (FK)    │ amount    │ item                  │
├───────────────┼─────────────────┼───────────┼───────────────────────┤
│ 101           │ 42 ─────────────┼─> $150.00 │ Mechanical Keyboard   │
│ 102           │ 42 ─────────────┼─> $35.00  │ USB-C Cable           │
└───────────────┴─────────────────┴───────────┴───────────────────────┘

Why Foreign Keys Are Essential:

1. Referential Integrity (No Ghost Data)

If someone attempts to insert an order with user_id = 999 when user 999 does not exist, the database engine rejects the transaction immediately:

INSERT INTO orders (user_id, amount) VALUES (999, 50.00);
-- ❌ ERROR: insert on table "orders" violates foreign key constraint

2. Cascade Actions (Clean Deletions)

When a parent record is deleted, foreign key constraints define what happens to child records:

  • ON DELETE CASCADE: Deleting user 42 automatically deletes all orders placed by user 42.
  • ON DELETE RESTRICT: Blocks user 42 from being deleted until their orders are handled.

Comparison Table

FeaturePrimary Key (PK)Foreign Key (FK)
ScopeInternal to its own tableCross-table reference
UniquenessMust be 100% UniqueCan contain duplicates (1 user has many orders)
NullabilityNEVER NullCan be Null (optional relationships)
IndexIndexed automaticallyShould be manually indexed for fast JOINs
CountMaximum 1 per tableMultiple per table allowed
SYSTEM DESIGN CHECK

Test Your Understanding

Quick architectural scenario challenge based on this breakdown.

SCENARIO

A 3rd-party payment gateway starts timing out with 504 errors during peak traffic.

Q1.How should a downstream dependency failure be handled to protect upstream service availability?

Comments –