🔑 Understanding Primary Keys
PRIMARY KEY is THE Most Important Decision
The primary key determines:
✓ Which server stores your data
✓ How data is sorted
✓ What queries you can run
✓ Performance of reads and writes
⚠️ Cannot be changed after table creation!
Primary Key Types
Simple Primary Key
One column = partition key
user_id UUID PRIMARY KEY,
name TEXT
);
-- All data for one user_id on same node
Composite Primary Key
Partition key + clustering columns
user_id UUID,
post_id TIMEUUID,
content TEXT,
PRIMARY KEY (user_id, post_id)
);
-- user_id = partition key
-- post_id = clustering column
Compound Partition Key
Multiple columns in partition key
category TEXT,
year INT,
post_id UUID,
title TEXT,
PRIMARY KEY ((category, year), post_id)
);
-- (category, year) = partition key
-- post_id = clustering column
How to Choose Primary Key
| Question | Answer | What to Do |
|---|---|---|
| How will I query? | By user_id | user_id = partition key |
| Do I need sorting? | Yes, by date | Add date as clustering column |
| Large partition? | 100M records per user | Add year/month to partition key |
| Hot partition? | One user = 90% of traffic | Redesign to distribute load |