Using a counter

To load data into a counter column, or to increase or decrease the value of the counter, use the UPDATE command. DataStax Enterprise rejects USING TIMESTAMP or USING TTL in the command to update a counter column.

Procedure

  1. Create a table for the counter column.

    CREATE TABLE IF NOT EXISTS cycling.popular_count (
      id UUID PRIMARY KEY,
      popularity counter
    );
  2. Loading data into a counter column is different than other tables. The data is updated rather than inserted.

    BEGIN COUNTER BATCH
    
      UPDATE cycling.popular_count
      SET popularity = popularity + 1
      WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47;
    
      UPDATE cycling.popular_count
      SET popularity = popularity + 125
      WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47;
    
      UPDATE cycling.popular_count
      SET popularity = popularity - 64
      WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47;
    
    APPLY BATCH;
    UPDATE cycling.popular_count 
    SET popularity = popularity + 2 
    WHERE id = 6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47;
  3. The popularity column has a value of 64.

    • CQL

    • Result

    SELECT *
    FROM cycling.popular_count;
     id                                   | popularity
    --------------------------------------+------------
     6ab09bec-e68e-48d9-a5f8-97e6fb4c9b47 |         64
    
    (1 rows)

Additional increments or decrements changes the value of the counter column.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 DataStax | Privacy policy | Terms of use

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: +1 (650) 389-6000, info@datastax.com