🔑 Primary Key Design
The PRIMARY KEY has two components: partition key and clustering columns. This determines data distribution and query patterns!
Real-World Examples
# Example 1: User Profiles (Simple)
CREATE TABLE users (
user_id uuid PRIMARY KEY,
name text,
email text,
created_at timestamp
);
-- Partition key: user_id
-- Each user = 1 partition = 1 row
-- Perfect for lookups: SELECT * FROM users WHERE user_id = ?
# Example 2: User Activity Timeline (With Clustering)
CREATE TABLE user_activity (
user_id uuid,
activity_time timestamp,
activity_type text,
details text,
PRIMARY KEY ((user_id), activity_time)
) WITH CLUSTERING ORDER BY (activity_time DESC);
-- Partition key: user_id
-- Clustering key: activity_time (sorted newest first)
-- Query: SELECT * FROM user_activity WHERE user_id = ? LIMIT 10
-- Returns: Last 10 activities for user
# Example 3: Time-Series Sensor Data (Composite Partition Key)
CREATE TABLE sensor_data (
sensor_id uuid,
date text, -- '2024-12-26'
hour int,
minute int,
temperature decimal,
humidity decimal,
PRIMARY KEY ((sensor_id, date), hour, minute)
);
-- Partition key: sensor_id + date (one partition per sensor per day)
-- Clustering keys: hour, minute (sorted chronologically)
-- Avoids huge partitions (splits by day)
-- Query: SELECT * FROM sensor_data
-- WHERE sensor_id = ? AND date = '2024-12-26'
# Example 4: Social Media Posts (With Multiple Clustering)
CREATE TABLE user_posts (
user_id uuid,
post_date date,
post_time timestamp,
post_id uuid,
content text,
likes counter,
PRIMARY KEY ((user_id, post_date), post_time, post_id)
) WITH CLUSTERING ORDER BY (post_time DESC, post_id ASC);
-- Partition key: user_id + post_date (one partition per user per day)
-- Clustering: post_time DESC (newest first), then post_id
-- Efficient queries: Get today's posts for user
-- Bounded partition size