Basic CQL Syntax Tutorial
Introduction to CQL
CQL (Cassandra Query Language) is the primary language for interacting with Apache Cassandra. It is designed to be similar to SQL, making it easier for developers familiar with SQL to work with Cassandra.
Key Components of CQL
CQL consists of several key components, including Keyspaces, Tables, and Columns. A keyspace is a container for tables, similar to a database in SQL, while tables contain rows and columns.
Basic Syntax Structure
The basic syntax for a CQL statement follows a clear structure:
COMMAND TABLE_NAME (COLUMN_DEFINITIONS);
Here, COMMAND can be CREATE, SELECT, INSERT, UPDATE, or DELETE, and TABLE_NAME is the name of the table you are interacting with.
Creating a Keyspace
To create a keyspace, use the CREATE KEYSPACE command, defining the replication strategy.
CREATE KEYSPACE my_keyspace WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
This command creates a keyspace named my_keyspace with a simple replication strategy.
Creating a Table
After creating a keyspace, you can create tables within it using the CREATE TABLE command.
CREATE TABLE my_keyspace.users (id UUID PRIMARY KEY, name TEXT, email TEXT);
This command creates a table named users with three columns: id, name, and email.
Inserting Data
To insert data into a table, use the INSERT INTO command.
INSERT INTO my_keyspace.users (id, name, email) VALUES (uuid(), 'Alice', 'alice@example.com');
This command inserts a new user into the users table with a unique UUID as the id.
Querying Data
To retrieve data from a table, use the SELECT command.
SELECT * FROM my_keyspace.users;
This command selects all rows from the users table.
Updating Data
To update existing data, use the UPDATE command.
UPDATE my_keyspace.users SET email = 'alice.new@example.com' WHERE id =
Replace <ID_HERE> with the actual UUID of the user you wish to update.
Deleting Data
To delete data from a table, use the DELETE command.
DELETE FROM my_keyspace.users WHERE id =
This command deletes the user with the specified UUID from the users table.
Conclusion
Understanding the basic syntax of CQL is essential for working with Apache Cassandra. With this knowledge, you can create keyspaces and tables, insert, query, update, and delete data effectively.