Create Cassandra Table

Author: Al-mamun Sarkar Date: 2020-09-19 14:35:37

CREATE TABLE command is used to create a table in Cassandra. It's pretty similar to the SQL CREATE TABLE statement.

 

Creating Table:

Syntax:

CREATE TABLE tablename(
   first_column_name Datatype PRIMARYKEY,
   second_column_name Datatype,
   third_column_name Datatype.
);
CREATE TABLE tablename(
   first_column_name Datatype,
   second_column_name Datatype,
   third_column_name Datatype,
   PRIMARY KEY (column_name)
);

Example:

CREATE TABLE employees(
   id int PRIMARY KEY,
   name text,
   city text,
   salary varint,
   phone varint 
);
CREATE TABLE users(
   id int,
   name text,
   city text,
   salary varint,
   phone varint,
   PRIMARY KEY (id)
);

Show all table:

DESCRIBE TABLES

Show details of a table:

DESCRIBE TABLE employees

 

Create a Table with a partition key and clustering key:

CREATE TABLE employee_by_car_make (
   car_make text, 
   id int, 
   car_model text, 
   PRIMARY KEY(car_make, id)
);

Here we use two primary key car_make and id. Here car_make is used as a partition key and id will be used as a clustering column. Into the nodes, data will be sorted by id. 

 

Use Multiple Clustering Column:

CREATE TABLE employee_by_car_make_sorted (
   car_make text, 
   id int,
   age int, 
   car_model text, 
   PRIMARY KEY(car_make, age, id)
);

Here car_make is the partition key and (age and id) are the clustering key. So data will be sorted based on age and id,

 

Use Multiple columns for Partition key:

CREATE TABLE employee_by_car_model (
   car_make text,  
   model text,
   id int,
   age int, 
   car_model text, 
   PRIMARY KEY((car_make, model), id)
);

Here (car_make, model) will be used for the partition key and id for the clustering key.