Cassandra data types define the kind of values a column can store, from simple integers and text to complex collections and user-defined structures. This article explains every built-in type, how to choose between them, and common pitfalls when modeling data in Apache Cassandra.
Formula
This page is a reference, not a calculator. The calculator above is a placeholder for the site’s template; the actual content below covers Cassandra data types. For the calculator: average pace (min/km) = finish time in minutes ÷ distance in km. Average speed (km/h) = distance ÷ (finish time ÷ 60).
Background: Why Cassandra’s Type System Is Different
Cassandra is a distributed NoSQL database designed for high write throughput and horizontal scaling. Unlike relational databases, Cassandra does not support joins or foreign keys. Instead, data is denormalized and stored in tables that are optimized for specific query patterns. The type system reflects this: every column must have a type, and that type is enforced at write time. But because data is replicated across nodes, types also affect how data is sorted, indexed, and compacted.
Cassandra’s types are defined in the CQL (Cassandra Query Language) specification. They fall into several families: primitive types (text, int, timestamp), collection types (list, set, map), tuple types, user-defined types (UDTs), and special types like counter and duration. Each type has a specific binary representation on disk, which matters for storage efficiency and performance.
Primitive Data Types
These are the building blocks. The most commonly used primitives are:
- text / varchar – UTF-8 encoded string. Use for names, descriptions, any human-readable text. In Cassandra,
textandvarcharare aliases. - int – 32-bit signed integer (range: -2^31 to 2^31-1). Use for counters, IDs, small numbers.
- bigint – 64-bit signed integer. Use when you need larger ranges, e.g., timestamps in milliseconds.
- double – 64-bit IEEE-754 floating point. Use for scientific or high-precision fractional values, but be aware of rounding.
- decimal – arbitrary-precision decimal. Use for money or exact arithmetic, but it’s slower than double.
- boolean – true/false.
- timestamp – date and time with millisecond precision, stored as milliseconds since epoch (UTC). Use for event times.
- uuid – universally unique identifier (version 1 or 4). Use for primary keys when you need globally unique IDs.
- timeuuid – UUID that embeds a timestamp. Useful for time-ordered unique IDs.
- blob – arbitrary binary data (byte array). Use for images, files, or serialized objects.
- inet – IP address (IPv4 or IPv6).
- date – date only (year, month, day).
- time – time of day with nanosecond precision.
- smallint / tinyint – smaller integers (16-bit and 8-bit) to save space.
- float – 32-bit floating point.
- varint – arbitrary-precision integer. Use when you need huge integers without a fixed limit.
Each primitive has a defined sort order. For example, int sorts numerically, text sorts lexicographically by UTF-8 bytes, timestamp sorts chronologically. This order is crucial for clustering columns because it determines how rows are stored on disk.
Collection Types: List, Set, Map
Cassandra supports three collection types, each designed for a specific use case:
- list – an ordered collection of values. Use when order matters and duplicates are allowed. Example:
list<text>for tags in a specific order. However, lists have a known limitation: updating an element requires reading the entire list, and concurrent updates can cause lost writes. Prefer sets or maps when possible. - set – an unordered collection of unique values. Use for tags, categories, or any set of distinct items. Sets are more efficient than lists for membership checks.
- map – a key-value pair collection. Use for attributes like
map<text, int>for product counts. Maps are useful for storing dynamic attributes that vary per row.
Collections have a maximum size of 64KB per cell (by default). This is a hard limit; if you exceed it, writes fail. For large or frequently updated collections, consider normalizing into separate rows instead. Also, collections are not meant for storing large amounts of data – they are optimized for small, bounded sets.
Tuple and User-Defined Types (UDT)
Tuples are fixed-length groups of values of different types. For example, tuple<int, text> can hold an integer and a string. Tuples are useful for simple groupings, but they are not as flexible as UDTs because they don’t have named fields.
User-defined types (UDTs) allow you to define a custom type with named fields, similar to a struct. For example:
CREATE TYPE address (street text, city text, zip int);
Then you can use it as a column type: address. UDTs are useful for nested data structures, but they add complexity. They are stored as a single cell, so the entire UDT is read/written as a unit. Avoid using UDTs for data that changes frequently; instead, use separate columns or a map.
Special Types: Counter, Duration, and Frozen
Three special types deserve attention:
- counter – a 64-bit signed integer that only supports increment/decrement operations. Use for counting events, likes, or views. Counters cannot be set to a specific value; you can only add or subtract. They are not allowed as primary key columns.
- duration – represents a length of time (e.g., 2 days, 3 hours). Stored as months, days, and nanoseconds. Use for time intervals, but note that duration cannot be used in primary keys or indexes.
- frozen – a keyword that makes a collection, tuple, or UDT immutable. For example,
frozen<list<int>>means the entire list must be replaced as a whole. Frozen types are required for certain operations like indexing or using collections in primary keys.
How to Choose the Right Data Type
Choosing a data type is a design decision that affects performance and storage. Here are practical guidelines:
- Use the smallest type that fits your data. For example, use
smallintinstead ofintif your values are under 32767. This saves disk space and memory. - Prefer
uuidortimeuuidfor primary keys to avoid hot spots. Sequential integers as partition keys can cause uneven distribution across nodes. - Use
timestampfor time-based queries. It sorts correctly and works with CQL date functions likedateOf(). - Avoid collections for large or frequently updated data. Each collection cell has a 64KB limit, and updates are not atomic across elements.
- Use
frozenwhen you need to index a collection or use it in a primary key. Frozen types are required for those cases. - For money, use
decimalorvarintto avoid floating-point rounding errors. For example, storing prices asdecimalwith appropriate scale is safer thandouble.
Common Problems and Misconceptions
One common mistake is using int for timestamps. If you store epoch seconds in an int, you’ll overflow in 2038 (the Y2038 problem). Use bigint or timestamp instead.
Another issue is assuming collections are ordered in a meaningful way. Lists preserve insertion order, but sets are unordered. If you need sorted output, sort in your application, not in the database.
A frequent misconception is that text and varchar are different. They are identical in Cassandra. Also, ascii is a separate type that only allows ASCII characters; use text for Unicode.
Finally, many users try to use a collection as a primary key. That is not allowed unless the collection is frozen. Even then, using a collection in a primary key is rarely a good idea because it makes queries awkward.
Comparison with Relational Database Types
Cassandra’s types are similar to SQL types, but with key differences:
- No auto-increment. Use
uuidortimeuuidinstead of an integer ID. - No
nullfor primary key columns. Primary key columns cannot be null, and they are part of the partition key. - No
textlength limit. In SQL,varchar(n)has a maximum length; in Cassandra,textis unbounded (but practical limits apply). - Collections are first-class. SQL has no direct equivalent to
listorset; you’d need a separate table. - Counters are special. SQL has
INTwith auto-increment, but Cassandra counters are designed for distributed increments.
Frequently Asked Questions
Can I change a column’s data type after creating a table? No. Cassandra does not support altering a column’s type. You must create a new table and migrate the data, or use a workaround like adding a new column with a different name.
What is the difference between uuid and timeuuid? A uuid is a random or version-1 UUID. A timeuuid is a version-1 UUID that embeds a timestamp. This means timeuuid can be sorted by time, and you can extract the timestamp using dateOf(). Use timeuuid when you need both uniqueness and time ordering.
Why can’t I use a counter as a primary key? Counters are designed to be incremented, not to identify rows. Allowing counters in primary keys would break the partition key logic and make it impossible to distribute data correctly. Use a regular type like uuid for primary keys.
What happens if I store a value larger than the collection limit? Writes will fail with an error. The default limit is 64KB per collection cell. You can increase it with the max_collection_elements setting, but it’s better to redesign your schema.
Can I use a map to store JSON-like data? Yes, but it’s not a full JSON type. Maps are flat key-value pairs; nested structures require UDTs or a text column with JSON serialization. For complex nested JSON, consider using a text column and parsing in your application.
Does text support Unicode? Yes, text stores UTF-8 encoded strings, so it supports any Unicode character. The ascii type only supports ASCII, which is a subset.
Related
Formula used
in t | Finish time | min | 50 | 0 in d | Distance | km | 10 | 0 | 100000 out pace | Average pace | min/km | t / d | 2 out speed | Average speed | km/h | d / (t / 60) | 2
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- OnePlus Watch 2 Teased? What We Know
- Vagrant vs Docker: Which Should You Use for Development?
- iQOO Neo 10 vs Neo 10R: Which Phone Should You Choose?
- Embedded OS: What They Do & When You Need One
- Best Sony E-Mount Lenses: Format & Subject Guide
- Samsung Galaxy Note Discontinued? Status Explained