In this post, we will discuss the various arithmetic operators supported in Cassandra and CQL version 3.x and above.
Cassandra Supported Arithmetic Operators
Apache Cassandra supports the following arithmetic operators:
- Addition – uses the plus (+) symbol for addition operations.
- Subtraction – uses the minus (-) for subtraction and unary negation.
- Multiplication – uses an asterisk (*) symbol for multiplication operations.
- Division – uses a forward slash (/) symbol for division operations.
- Modulo – uses the percentage (%) symbol for remainder division operations.
Keep in mind that operators has a higher and lower precedence level. For example, a division and modulo operator has a higher precedence than addition and subtraction operator.
Cassandra Operator Return Values
The following table shows the return value of various operands on left/right operands:
Example
The example below shows how to use the Cassandra arithmetic operators:
... 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));
Insert sample data as:
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);
Finally, verify results exists in the table.
Output:
----+--------+----------
1 | 115 | user2
0 | 210 | user1
2 | 202 | user3
4 | 216 | user5
3 | 212 | user4
(5 rows)
Calculate Average Height.
In this example, we use the sum aggregate function to determine the total of all heights. We then use the division operator to find the mean of the heights.
The query above should return an output as shown:
------------------------
191
(1 rows)
Conclusion
In this post, we discussed the various types of arithmetic operators supported by the latest Apache Cassandra version.