Day 8: Cassandra Lab Practice – Batch Operations

Day 8: Batch Operations in Cassandra

๐ŸŽฏ Objective:

Learn how to perform multiple inserts, updates, or deletes in a single batch using the BATCH statement in CQL.


๐Ÿ“˜ 1. What is a Batch?

  • A BATCH lets you group multiple CQL statements into a single request.
  • Use carefully — it is not meant for high-performance mass inserts.
  • Best use case: multiple updates on the same partition key.

๐Ÿงฉ 2. Basic Batch Syntax

BEGIN BATCH
  <insert/update/delete statement 1>;
  <insert/update/delete statement 2>;
APPLY BATCH;

๐Ÿงช 3. Example: Batch Insert into employee Table

BEGIN BATCH
  INSERT INTO test_lab.employee (emp_id, name, department, joined_on)
  VALUES (uuid(), 'Ravi', 'HR', toTimestamp(now()));

  INSERT INTO test_lab.employee (emp_id, name, department, joined_on)
  VALUES (uuid(), 'Meera', 'Finance', toTimestamp(now()));
APPLY BATCH;

๐Ÿ”ง 4. Example: Batch Update

BEGIN BATCH
  UPDATE test_lab.employee
  SET department = 'Tech'
  WHERE emp_id = <UUID1>;

  UPDATE test_lab.employee
  SET department = 'Admin'
  WHERE emp_id = <UUID2>;
APPLY BATCH;

⚠️ 5. Best Practices for Batch

Good Practice Bad Practice
Same partition key Different partition keys
Small number of statements (3–5) Very large batches (>50)
Related operations (atomic update) Massive bulk loading

๐Ÿ›‘ 6. What Happens on Error?

  • If any query in batch fails, the entire batch is aborted.
  • Always validate queries individually before batching.

๐Ÿงช Day 8 Lab Tasks

  1. Use BATCH to insert 2–3 employees
  2. Update multiple rows using a batch
  3. Try inserting into different tables in one batch
  4. Observe performance and error handling

Checklist

Task Done
Used BEGIN BATCH ... APPLY BATCH
Inserted multiple rows in one batch
Performed batch updates
Understood batch best practices