Curriculum
In Cassandra, a table is defined as a collection of related data items that are organized in rows and columns. The data model in Cassandra is based on tables, which are grouped into keyspaces. In this tutorial, we will learn how to create a table in Cassandra using the CQL (Cassandra Query Language) command-line shell.
To create a table in Cassandra, the basic syntax is as follows:
CREATE TABLE [IF NOT EXISTS] keyspace_name.table_name ( column_name1 data_type [PRIMARY KEY | CLUSTERING ORDER | STATIC], column_name2 data_type, column_name3 data_type, ... [PRIMARY KEY (column_name1, column_name2, ...)] ) [WITH [option1=value1] AND [option2=value2] ...];
Explanation:
CREATE TABLE
: This keyword is used to create a new table in Cassandra.IF NOT EXISTS
: This is an optional clause that ensures that the table is created only if it doesn’t already exist.keyspace_name
: This is the name of the keyspace that the table belongs to.table_name
: This is the name of the table that is being created.column_name
: This is the name of a column in the table.data_type
: This specifies the data type of the column. Cassandra supports a variety of data types, including text, integer, boolean, timestamp, and more.PRIMARY KEY
: This specifies the primary key of the table, which is a unique identifier for each row in the table. The primary key can be composed of one or more columns, and must be defined as part of the CREATE TABLE statement.CLUSTERING ORDER
: This specifies the ordering of rows within each partition. This option is only applicable for tables with a composite primary key.STATIC
: This is an optional keyword that is used to indicate that the column is a static column. Static columns have the same value across all rows within a partition.Example: Let’s create a table called users
in the developerpublish
keyspace, with columns for user_id
, name
, email
, and age
. We will use the user_id
column as the primary key.
CREATE TABLE developerpublish.users ( user_id int PRIMARY KEY, name text, email text, age int );
In this example, we have created a table called users
in the developerpublish
keyspace. The table has four columns: user_id
, name
, email
, and age
. The user_id
column is defined as the primary key, with the int
data type.
In this tutorial, we have learned how to create a table in Cassandra using the CQL command-line shell. We have covered the syntax and components of the CREATE TABLE statement, and provided an example of how to create a table with a primary key. By understanding how to create tables in Cassandra, you can begin to build more complex data models to store and manage your data.