Data Definition Language (DDL) in CQL
What is Data Definition Language (DDL)?
Data Definition Language (DDL) is a subset of SQL (Structured Query Language) used to define and manage all aspects of a database schema. In Cassandra, which uses CQL (Cassandra Query Language), DDL commands allow users to create, modify, and delete database objects such as keyspaces and tables. DDL commands are crucial for defining the structure of the database and ensuring that it meets the required data model.
Key DDL Commands in CQL
CQL provides several important DDL commands. The most commonly used ones include:
- CREATE KEYSPACE
- CREATE TABLE
- ALTER TABLE
- DROP TABLE
- USE KEYSPACE
Creating a Keyspace
A keyspace in Cassandra is similar to a database in traditional RDBMS. It defines how data is replicated across the nodes. To create a keyspace, you can use the CREATE KEYSPACE
command.
Example:
In this example, we created a keyspace named my_keyspace
with a replication strategy called SimpleStrategy
and a replication factor of 1.
Creating a Table
Once a keyspace is created, you can create tables within it. The CREATE TABLE
command allows you to define the structure of the table, including its columns and data types.
Example:
This command creates a table named users
with three columns: user_id
(of type UUID), name
(of type TEXT), and email
(of type TEXT). The user_id
column is defined as the primary key.
Altering a Table
The ALTER TABLE
command is used to modify existing tables, such as adding new columns or changing the properties of columns.
Example:
In this example, we added a new column called age
of type INT to the users
table.
Dropping a Table
If you need to remove a table from a keyspace, you can use the DROP TABLE
command.
Example:
This command will delete the users
table from the current keyspace.
Using a Keyspace
Before you can execute DDL commands on a specific keyspace, you must first select it using the USE
command.
Example:
This command sets the current keyspace to my_keyspace
, allowing you to perform subsequent commands within that context.
Conclusion
Understanding DDL in CQL is essential for managing the structure of your Cassandra database. By using the commands outlined in this tutorial, you can effectively create, modify, and delete keyspaces and tables, ensuring that your data model aligns with your application’s requirements.