Day 3: Cassandra Lab Practice – Creating Tables & Primary Keys

Day 3: Creating Tables & Understanding Primary Keys

🎯 Objective:

Understand how to create tables in Cassandra with proper primary key design using partition keys and clustering keys.


📘 1. Components of a Table

A Cassandra table has:

  • Column definitions

  • Primary Key = Partition Key (+ optional Clustering Columns)

CREATE TABLE keyspace_name.table_name (
   column1 datatype,
   column2 datatype,
   ...
   PRIMARY KEY ((partition_key), clustering_column1, ...)
);

🔑 2. Primary Key Concepts

Partition Key

  • Used to distribute data across nodes

  • Determines which node stores the row

Clustering Key

  • Determines the order of rows within a partition

Example:

PRIMARY KEY ((student_id)) -- Only partition key
PRIMARY KEY ((class_id), roll_no) -- Partition by class_id, cluster by roll_no

🛠️ 3. Practice: Create Tables

➤ Example 1: Simple Primary Key

CREATE TABLE test_lab.employee (
  emp_id uuid PRIMARY KEY,
  name text,
  department text,
  joined_on timestamp
);

➤ Example 2: Composite Primary Key (Partition + Clustering)

CREATE TABLE test_lab.attendance (
  class_id text,
  student_id uuid,
  date date,
  status text,
  PRIMARY KEY ((class_id), date)
);

➤ Example 3: Compound Partition Key

CREATE TABLE test_lab.exam_scores (
  exam_id text,
  subject text,
  student_id uuid,
  score int,
  PRIMARY KEY ((exam_id, subject), student_id)
);

🔍 4. Inspect the Table Structure

DESCRIBE TABLE test_lab.attendance;

Look for:

  • Partition key

  • Clustering columns

  • Column types


🧪 Day 3 Lab Tasks

  1. Create employee, attendance, and exam_scores tables with proper keys

  2. Understand difference between:

    • Simple primary key

    • Composite key

    • Compound partition key

  3. Use DESCRIBE TABLE to validate structure

  4. Run queries with SELECT * and see how clustering columns affect order (covered more in Day 4)


Checklist

Task Done
Understood partition key vs clustering key
Created 3 different types of tables
Described table schema and keys