What type should I use to store values like "999999.99" in Cassandra?

45 Views Asked by At

I wanna add a price column to my table to be able to store values from 0.0 to 999999.99. I tried price DECIMAL(8,2) but it seems it doesn't work. How can I store such a value?

I am also wondering to know if there would be any pre-post processing needed after that because I use NodeJS/TypeScript in backend that handles all numeric values using number type!

I also like to know if is it a better idea to use string type insted?

EDIT: For example if I try

CREATE TABLE IF NOT EXISTS products.test(
  id TEXT PRIMARY KEY,
  price DECIMAL(8,2));
  

I get:

SyntaxException: line 3:15 no viable alternative at input '(' (... TEXT PRIMARY KEY, price DECIMAL

But the following works with no problems:

CREATE TABLE IF NOT EXISTS products.test(
  id TEXT PRIMARY KEY,
  price INT);
2

There are 2 best solutions below

0
Madhavan On

You could leverage decimal type or even use float data types in Cassandra. See https://cassandra.apache.org/doc/latest/cassandra/cql/types.html for more details. And, with NodeJS Driver, https://docs.datastax.com/en/developer/nodejs-driver/latest/features/datatypes/ the CQL decimal data type maps to BigDecimal JS type. float CQL data type maps to Number JS type and so on.

0
Erick Ramirez On

Your syntax is incorrect which is the reason for the SyntaxException.

It is not possible to specify the precision in CQL since the decimal type is a variable-precision Java type.

Simply declare the column as decimal type, for example:

CREATE TABLE decimals (
    id int PRIMARY KEY,
    price decimal
)

and deal with the precision in your code instead. Cheers!