In this article, you will learn how to use the Apache Cassandra TRUNCATE command. This command allows you to remove all the data from a table without deleting the table or its schema.
In simple terms, the TRUNCATE command allows you to reset the data stored in a table allowing you to restore or insert new data.
Cassandra Truncate Command Syntax
The TRUNCATE command syntax is as shown:
You can omit the TABLE keyword in the syntax above. The command will perform a similar action.
Keep in mind that the TRUNCATE command sends the JMX command to all the nodes in the cluster that contains the data of the target. This allows the nodes to synchronize and stay up to date with the recent data changes. If either of the nodes in the cluster is down, the command will fail and return an error.
Creating Sample Table and Data
For illustration purposes, we will create a sample keyspace and table. The commands are as shown in the snippets below:
... with replication = {
... 'class': 'SimpleStrategy',
... 'replication_factor': 1};
cqlsh> USE height_info;
cqlsh:height_info> CREATE TABLE recipients(
... id int,
... username text,
... height int,
... PRIMARY KEY(id, height));
We can then insert sample data as shown in the commands below:
cqlsh:height_info> INSERT INTO recipients(id, username, height) values (1, 'user2', 115);
cqlsh:height_info> INSERT INTO recipients(id, username, height) values (2, 'user3', 202);
cqlsh:height_info> INSERT INTO recipients(id, username, height) values (3, 'user4', 212);
cqlsh:height_info> INSERT INTO recipients(id, username, height) values (4, 'user5', 216);
Example Truncation Operation
The data stored in the table before truncation is as shown:
We can truncate the table as shown:
Finally, we can confirm the data is removed from the table as:
You will notice that the table still exists including all the schema definitions. However, the data from the table has been removed leaving an empty table.
Keep in mind that the TRUNCATE operation is irreversible. Be cautious in its usage and potential data loss.
Conclusion
In this post, you learned how to remove all the data from a table while preserving the table schema using the CQL TRUNCATE command.