cqlsh host port -u user -p pass★Connect to a node (default9042).USE keyspace;★Set the working keyspace for the session.DESCRIBE keyspaces;List keyspaces.DESCis the alias.DESCRIBE table t;★Show a table's full schema (CREATE stmt).SOURCE 'schema.cql';Run CQL statements from a file.COPY t TO 't.csv';Bulk export a table to CSV (andFROMto import).CONSISTENCY QUORUM;Set consistency for this session.TRACING ON; EXPAND ON;Debug latency; print wide rows vertically.
CREATE KEYSPACE IF NOT EXISTS app WITH replication = {'class':'NetworkTopologyStrategy','dc1':3};★Production default — per-datacenter replica count.CREATE KEYSPACE dev WITH replication = {'class':'SimpleStrategy','replication_factor':1};Single-DC / dev only — never for multi-DC.ALTER KEYSPACE app WITH replication = {…};Change RF, then runnodetool repair.DROP KEYSPACE app;destroysDeletes the keyspace and every table in it.
CREATE TABLE users (★
id uuid PRIMARY KEY,
email text, name text);Simple key —idis both partition & only key.CREATE TABLE events (★
user_id uuid, ts timestamp, kind text,
PRIMARY KEY ((user_id), ts))
WITH CLUSTERING ORDER BY (ts DESC);Partition by user, rows newest-first. The core pattern.PRIMARY KEY ((a, b), c, d)Composite partition key(a,b)+ clusteringc,d.ALTER TABLE users ADD phone text;Add a column (cheap — no data rewrite).DROP TABLE users;destroysRemoves the table and all its data.
PRIMARY KEY ( partition, clustering… )First component(s) = partition key; the rest sort within it.partition key★Hashed to a token → picks the node. Every query must supply it.clustering keySorts & uniquely locates rows inside a partition; enables range scans.no partition key in WHEREantiForces a full-cluster scan →ALLOW FILTERING. Avoid.keep partitions boundedAim < 100 MB / < 100k rows each — huge partitions kill nodes.
INSERT INTO users (id, email)★
VALUES (uuid(), 'a@b.io');Insert = upsert; same key silently overwrites.INSERT INTO … USING TTL 86400;Row expires after N seconds (auto-delete).UPDATE users SET name='Zoe'★
WHERE id=?;Updates the row, or creates it if absent (upsert).UPDATE t SET n = n + 1 WHERE …;Counter columns — increment/decrement only.INSERT … IF NOT EXISTS;LWTLightweight transaction — Paxos, much slower.
SELECT * FROM events★
WHERE user_id=?;Read a whole partition — the fast path.WHERE user_id=? AND ts > ?★Range on the clustering key — always cheap.ORDER BY ts DESC LIMIT 20;Only along the clustering order;LIMITcaps rows.SELECT token(user_id), * FROM …Inspect the token that placed a partition.SELECT … ALLOW FILTERING;careScans/filters off-key columns — unpredictable at scale.
DELETE email FROM users WHERE id=?;Delete one column (sets it NULL).DELETE FROM users WHERE id=?;★Delete a whole row by primary key.DELETE FROM events WHERE user_id=?;tombstonesDeletes a partition → many tombstones; hurts later reads.TRUNCATE users;destroysWipes every row instantly, all nodes.
text · varchar · asciiUTF-8 / ASCII strings.int · bigint · varint · decimal · doubleNumbers;counterfor distributed counts.uuid · timeuuid★timeuuidembeds time & sorts — great clustering key.timestamp · date · time · durationTemporal types (ms precision on timestamp).boolean · blob · inetFlags, raw bytes, IP addresses.
tags set<text>, log list<text>,
attrs map<text,text>Three collection types; keep them small (< a few KB).UPDATE t SET tags = tags + {'vip'} …★Add to a set/list without reading first.UPDATE t SET attrs['k'] = 'v' …Set / update a single map entry.CREATE TYPE address (city text, zip text);User-defined type; embed asfrozen<address>.
BEGIN BATCH
INSERT INTO … ;
UPDATE … ;
APPLY BATCH;Logged batch = atomic across statements.BEGIN UNLOGGED BATCH … APPLY BATCH;No atomicity guarantee — only for one partition.multi-partition batchantiSpanning partitions to "save round-trips" hurts — don't.
CREATE INDEX ON users (email);2i secondary index — OK for low cardinality only.CREATE CUSTOM INDEX ON t (col)★
USING 'StorageAttachedIndex';SAI (Cassandra 5.0) — the modern, faster index.CREATE MATERIALIZED VIEW mv AS
SELECT * FROM base WHERE … PRIMARY KEY (…);Auto-maintained table keyed differently for a 2nd query.
ONE · LOCAL_ONEFastest; 1 replica must respond. Weakest.QUORUM = ⌊RF/2⌋ + 1★Majority of replicas.LOCAL_QUORUM= per-DC.ALL · EACH_QUORUMStrongest / cross-DC; least available.R + W > RF★The rule for strong consistency (e.g. QUORUM read + write).
CREATE ROLE app WITH PASSWORD='x'
AND LOGIN=true;Create a login role (replacesCREATE USER).GRANT SELECT ON app.users TO app;Grant a permission on a resource.LIST ROLES; LIST PERMISSIONS;Audit who can do what.DROP ROLE app;careRemoves the role & its grants.
nodetool status★Nodes, state (UN=up/normal), load, ownership %.nodetool repair★Reconcile replicas — run routinely (< gc_grace).nodetool flush · cleanupMemtable→SSTable; drop data no longer owned.nodetool tablestats · tpstatsPer-table metrics; thread-pool / dropped msgs.
1. give the full partition keyEquality on every partition-key column — required.2. clustering keys left-to-rightRestrict them in definition order, no gaps.3. range only on the last one usedEarlier clustering cols need=; one may use< >.4. ORDER BY follows clusteringYou can only sort along the defined order (or reversed).else → ALLOW FILTERINGsmellIf you need it, the table is modelled for the wrong query.