Cassandra – Create Table

In this tutorial, we will learn about the CREATE Table command in Cassandra which allows us to create new table using cqlsh by providing the valid column names, data types.

Syntax:

CREATE TABLE keyspace_name.table_name
( column_definition, column_definition, ...)
WITH property AND property ...

Example:

CREATE TABLE LearningStore.users (
user_id int PRIMARY KEY,
created_date timestamp,
first_name text,
last_name text,
email text
);

In the above example, LearningStore is keyspace and user_id is where the primary key which consists of only one column.

Compounded PrimaryKey:

This consists more than one column as primary key. Cassandra treats the first column as partition key.

CREATE TABLE LearningStore.users (
user_idint PRIMARY KEY,
created_date timestamp,
first_name text,
last_name text,
email text,
PRIMARY KEY (user_id, first_name)
);

Column definition Syntax:

column_namecql_type
| column_namecql_type PRIMARY KEY
| PRIMARY KEY ( partition_key )
| column_namecollection_type

Example:

CREATE TABLE LearningStore.users (
user_idint PRIMARY KEY,
created_date timestamp,
first_name text,
last_name text,
emails set<text>,
lessons list<int>,
tobecompleted map<timestamp, text>
);

Validate the Table Creation

Make sure that you are in LearningStoreKeyspace before giving the below command.

cqlsh:LearningStore> select * from users;