CQL Data Types
Master Cassandra's rich type system! From simple text and numbers to complex collections and UUIDs.
๐ The Story: Sarah's E-Commerce Disaster
Sarah just launched her first e-commerce app. She stored EVERYTHING as TEXT because "it's simple!" But then Black Friday happened...
โ The WRONG Way (Everything as TEXT)
What Went Wrong:
- ๐ธ Price sorting broke: "9.99" came BEFORE "19.99" alphabetically!
- ๐ Can't calculate totals: Can't SUM text
- ๐๏ธ Date filtering disaster: String comparison chaos
Result: $50,000 in lost Black Friday sales! ๐ฑ
โ The RIGHT Way (Proper Types)
Next Black Friday: Zero crashes! Revenue up 40%! ๐
๐ค Simple Data Types
TEXT / VARCHAR
Purpose: Store letters, words, sentences - any UTF-8 text!
Max Size: Up to 2GB (but keep it reasonable - a few KB typical)
๐ฆ How Cassandra Stores It:
Internally: UTF-8 encoded byte array
Example: "Hello" โ [48 65 6C 6C 6F] (hex bytes)
Real Examples:
Use Cases:
- โ Names (any language!)
- โ Email addresses, URLs
- โ Product descriptions
- โ Comments, reviews, posts
- โ JSON strings (store small JSON)
BOOLEAN
Purpose: True or False!
Use Cases:
- Is email verified?
- Is order completed?
- Is user active?
- Agreed to terms?
DATE
Purpose: Calendar dates (no time)
Format: YYYY-MM-DD
Use Cases:
- Birthdays
- Publication dates
- Event dates
TIMESTAMP
Purpose: Date AND exact time!
Use Cases:
- Order placed time
- Last login
- Message sent time
๐ข Numeric Data Types
INT
Purpose: Whole numbers (no decimals)
Range: -2,147,483,648 to 2,147,483,647
Storage: 4 bytes (32 bits)
๐ฆ How Cassandra Stores It:
Binary format: 4 bytes
Example: 42 โ 0x0000002A (hex)
Example: -100 โ 0xFFFFFF9C (2's complement)
Real Examples:
Use Cases:
- โ Age, year, count
- โ Quantity, stock levels
- โ Scores, points, ratings
- โ Sequential IDs (small scale)
- โ Money (use DECIMAL!)
- โ Very large numbers (use BIGINT)
DECIMAL
Purpose: Exact decimals - PERFECT for money!
Precision: Arbitrary precision (no rounding errors)
Storage: Variable (depends on precision)
๐ฆ How Cassandra Stores It:
BigDecimal format: [scale][unscaled value]
Example: 19.99 โ scale=2, value=1999
Stored as: 0x00 0x02 0x07 0xCF
NO rounding - 100% exact! โ
Real Money Examples:
Use Cases:
- โ ๐ต Money, prices, salaries
- โ Tax calculations
- โ Financial transactions
- โ Accounting, invoices
- โ Exact measurements
- โญ Anytime precision matters!
โ ๏ธ NEVER use FLOAT for money!
FLOAT: 0.1 + 0.2 = 0.30000000000000004 โ
BIGINT
Purpose: VERY large numbers
Use Cases:
- Timestamps (ms)
- Global counters
- Large IDs
FLOAT
Purpose: Approximate decimals
Warning: May have rounding!
Use Cases:
- GPS coordinates
- Temperature
- Scientific data
Money: NEVER use FLOAT!
โ WRONG:
โ CORRECT:
๐ UUID Types
UUID
Purpose: Globally unique random identifier
Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx (36 chars)
Storage: 16 bytes (128 bits)
Uniqueness: 340 undecillion possible values!
๐ฆ How Cassandra Stores It:
Binary: 128-bit (16 bytes) number
Display: 550e8400-e29b-41d4-a716-446655440000
Internal: [55 0E 84 00 E2 9B 41 D4 A7 16 44 66 55 44 00 00]
Real Examples:
Use Cases:
- โ Primary keys (distributed systems!)
- โ User IDs
- โ Order IDs, Transaction IDs
- โ Session IDs, API keys
- โ Any globally unique identifier
โจ Why UUID is amazing:
โข Generate IDs on any node - no coordination!
โข Collision probability: 1 in 340 undecillion ๐คฏ
โข Perfect for distributed systems
TIMEUUID
Purpose: UUID with embedded timestamp!
Benefit: Automatically sortable by creation time
Storage: 16 bytes (128 bits) - same as UUID
Magic: Extract timestamp from the ID itself!
๐ฆ How Cassandra Stores It:
Structure: [timestamp][clock_seq][node_id]
Example: d2177dd0-eaa2-11de-a572-001b779c76e3
โข First 60 bits: timestamp (100-nanosecond intervals)
โข Sorted chronologically automatically! ๐ฏ
Real Examples:
Use Cases:
- โ Chat messages (sorted by time)
- โ Event logs, activity streams
- โ Time-series data
- โ Audit trails
- โ IoT sensor readings
- โญ Anything needing time + uniqueness!
๐ TIMEUUID Benefits:
โข Unique ID + Timestamp in one! 2-in-1!
โข Automatic chronological sorting
โข No separate created_at column needed
โข Perfect for time-series data
๐ฆ Collection Types
LIST
Purpose: Ordered, allows duplicates
Use Cases:
- Tags list
- Shopping cart items
- Recent searches
SET
Purpose: Unique values only
Use Cases:
- Unique categories
- Skills
- Interests
MAP
Purpose: Key-value pairs
Use Cases:
- User preferences
- Metadata
- Attributes
๐ฅ๏ธ Interactive Console
๐ How to Choose the Right Data Type
Follow this decision tree to pick the perfect type every time!
๐ผ Interview Questions
Answer:
Use DECIMAL when:
- ๐ฐ Storing money (prices, salaries, taxes)
- Exact precision required
- No rounding errors acceptable
- Financial calculations
Use FLOAT when:
- Scientific calculations (acceptable approximation)
- GPS coordinates
- Temperature readings
- Statistical data where tiny errors OK
Key Insight: FLOAT can have rounding errors like 19.99 becoming 19.989999. DECIMAL is EXACT - perfect for money!
Answer:
Use UUID when:
- Just need unique ID
- No time-based sorting needed
- User IDs, Product IDs
- Session tokens
Use TIMEUUID when:
- Need automatic time-based sorting
- Messages, Events, Logs
- Want to extract timestamp from ID
- Time-series data
Example: Chat app messages use TIMEUUID so messages automatically sort by time!
Answer:
LIST:
- โ Ordered (maintains insertion order)
- โ Allows duplicates
- Use for: Shopping cart, recent searches, to-do items
SET:
- โ Unordered
- โ NO duplicates (automatically removes)
- Use for: Unique tags, skills, categories
Answer: NO! (with rare exceptions)
Why not?
- Data already stored in old format
- Converting could lose data or cause errors
- Cassandra prioritizes data safety
Solution if you MUST change:
- Add new column with correct type
- Migrate data (write script to copy/convert)
- Update application to use new column
- Drop old column (optional)
Lesson: Choose types carefully upfront! ๐ฏ
Answer:
COUNTER is a special type that can ONLY be incremented or decremented - you cannot set it directly!
Special Rules:
- โ Cannot use INSERT (must use UPDATE)
- โ Can only do += or -= operations
- Perfect for: page views, likes, downloads
Why? COUNTER is distributed across nodes. Using += ensures consistency!
๐ Data Type Comparison Matrix
๐ Chapter Summary
You now understand CQL data types!
- Simple Types: TEXT, INT, BOOLEAN, DATE, TIMESTAMP
- Numeric: INT, BIGINT, DECIMAL (money!), FLOAT, DOUBLE
- UUID: Random IDs, TIMEUUID for time-sorted IDs
- Collections: LIST (ordered), SET (unique), MAP (key-value)
๐ฏ Golden Rule: Use the RIGHT type for the RIGHT data!
๐ข Real-World Production Examples
๐ต Spotify: Music Duration Storage Crisis
The Problem: Stored song duration as TEXT: "3:45", "4:12"
Issues:
- Can't calculate total playlist duration
- Can't sort by length
- Can't find songs > 4 minutes
The Fix:
Result: Playlist calculations work! Sorting perfect! Users happy! ๐
๐ Shopify: The FLOAT Price Disaster
The Problem: Used FLOAT for product prices
Impact: Customers charged $19.99, database showed $19.98 โ Accounting nightmare!
The Fix:
Result: Accounting matched perfectly. CFO stopped panicking! ๐ฐ
Responsive Ad