Search code examples
cassandracql3

Is it possible to update one value and delete another one by a single Cassandra CQL query?


Given a table:

CREATE TABLE t (
    k text,
    v1 int,
    v2 int,
    PRIMARY KEY (k)
)

Is it possible to set v1 to some value and delete (set to null) v2 with a single query? Something like:

UPDATE t SET v1=100, v2=NULL WHERE k='somekey';

I have looked through the docs, but found nothing.

It would be a nice to have feature for two reasons:

  • Updating a table with a lots of columns using prepared statements is really painful now.
  • If my understanding is correct, row update by a single query should be atomic, whereas there are no guarantees for two consequent queries.

Solution

  • The query you suggested works (at least) in CQL3:

    cqlsh:ks> UPDATE t SET v1=100, v2=NULL WHERE k='somekey';
    cqlsh:ks> select * from t;
    
     k       | v1  | v2
    ---------+-----+------
     somekey | 100 | null
    

    If you want to do more complicated atomic updates e.g. across different row keys or column families, you can wrap separate UPDATEs in BEGIN BATCH...APPLY BATCH.