Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Basic CQL Commands Tutorial

Introduction to CQL

Cassandra Query Language (CQL) is a query language for the Apache Cassandra database. It is designed to be similar in syntax to SQL, making it easier for users familiar with SQL to transition to using Cassandra. CQL allows users to create, modify, and query data stored in Cassandra.

Connecting to Cassandra

Before executing any CQL commands, you need to connect to a Cassandra instance. The most common way to do this is through the cqlsh command-line interface. You can start it by simply typing cqlsh in your terminal.

Command:

cqlsh

Creating a Keyspace

A keyspace in Cassandra is a namespace that defines how data is replicated on the nodes. You can create a keyspace using the following command:

Command:

CREATE KEYSPACE my_keyspace WITH REPLICATION = {'class': 'SimpleStrategy', 'replication_factor': 1};

In this command, my_keyspace is the name of the keyspace, and it uses the SimpleStrategy replication strategy with a replication factor of 1.

Using a Keyspace

To use a keyspace after creating it, you can use the USE command:

Command:

USE my_keyspace;

Creating a Table

Once you have a keyspace, you can create tables to store your data. The syntax for creating a table is as follows:

Command:

CREATE TABLE users (id UUID PRIMARY KEY, name text, age int);

In this example, we create a table named users with three columns: id, name, and age.

Inserting Data

To insert data into a table, you can use the INSERT command:

Command:

INSERT INTO users (id, name, age) VALUES (uuid(), 'Alice', 30);

Here, we insert a new user with a unique ID, name 'Alice', and age 30 into the users table.

Querying Data

You can retrieve data from a table using the SELECT command:

Command:

SELECT * FROM users;

This command retrieves all records from the users table.

Updating Data

To update existing data, you can use the UPDATE command:

Command:

UPDATE users SET age = 31 WHERE name = 'Alice';

This command updates Alice's age to 31.

Deleting Data

To delete data from a table, you can use the DELETE command:

Command:

DELETE FROM users WHERE name = 'Alice';

This command deletes the record of the user named Alice from the users table.

Conclusion

This tutorial covered basic CQL commands that are essential for working with Cassandra. By mastering these commands, you can effectively manage your data in Cassandra.