Cassandra cqlsh Reference Guide
For those who have used mysql or psql, cqlsh will feel familiar—a command-line interface for running queries, exploring schemas, and managing data. It ships with Cassandra and has been the default way to interact with clusters since CQL replaced Thrift in 2011.
cqlsh is written in Python, which means Python must be installed, and occasionally version compatibility issues arise. It is functional but basic: no AI assistance, minimal autocompletion, and output limited to text tables. For a more modern alternative, check out CQLAI—it handles everything cqlsh does plus AI-powered query generation, Parquet exports, and better formatting.
But cqlsh is everywhere. It is on every Cassandra node, requires no installation, and every tutorial assumes its use. This reference covers everything needed to be productive with it.
Installation and Set up
Section titled “Installation and Set up”Included with Cassandra
Section titled “Included with Cassandra”# cqlsh is included in Cassandra installation/opt/cassandra/bin/cqlsh
# Or if in PATHcqlshStandalone Installation
Section titled “Standalone Installation”# Python 3.6–3.11 required# cqlsh is included with Cassandra; for standalone use, install the driver:pip install cassandra-driverPython Version Compatibility
cqlsh requires Python 3.6 through 3.11. Python 3.12+ may not be fully compatible. Use python3 --version to verify.
Connecting to Cassandra
Section titled “Connecting to Cassandra”Basic Connection
Section titled “Basic Connection”# Connect to localhostcqlsh
# Connect to specific hostcqlsh 10.0.0.1
# Connect to specific host and portcqlsh 10.0.0.1 9042
# With authenticationcqlsh -u username -p password 10.0.0.1
# Prompt for password (more secure)cqlsh -u username 10.0.0.1# Enter password when promptedConnection with SSL
Section titled “Connection with SSL”# Basic SSL (certificate paths configured in cqlshrc)cqlsh --ssl 10.0.0.1SSL Configuration
SSL certificates must be configured in ~/.cassandra/cqlshrc under the [ssl] section. There is no command-line flag for specifying certificate files directly.
cqlshrc Configuration
Section titled “cqlshrc Configuration”[authentication]username = cassandrapassword = cassandra
[connection]hostname = 10.0.0.1port = 9042timeout = 10
[ssl]certfile = /path/to/ca-cert.pemvalidate = true# userkey = /path/to/client-key.pem# usercert = /path/to/client-cert.pem
[cql]version = 3.4.5
[ui]color = onfloat_precision = 5timezone = UTCencoding = utf8Command-Line Options
Section titled “Command-Line Options”Usage: cqlsh [options] [host [port]]
Port Specification
Port is a positional argument, not a flag. Use cqlsh hostname 9042 (not --port).
| Option | Description |
|---|---|
-u, --username | Username for authentication |
-p, --password | Password for authentication |
-k, --keyspace | Keyspace to use |
-f, --file | Execute commands from file |
-e, --execute | Execute command and exit |
--ssl | Use SSL (configure certs in cqlshrc) |
--connect-timeout | Connection timeout in seconds |
--request-timeout | Request timeout in seconds |
--encoding | Character encoding |
--cqlversion | CQL version to use |
--debug | Show debug output |
Examples
Section titled “Examples”# Execute single commandcqlsh -e "SELECT * FROM system.local"
# Execute filecqlsh -f /path/to/script.cql
# Connect to specific keyspacecqlsh -k my_keyspace 10.0.0.1
# With timeoutcqlsh --connect-timeout=10 --request-timeout=60 10.0.0.1Shell Commands
Section titled “Shell Commands”Help Commands
Section titled “Help Commands”HELP; -- Show all commandsHELP <command>; -- Help for specific commandHELP SELECT; -- Help for SELECTNavigation Commands
Section titled “Navigation Commands”-- Use keyspaceUSE my_keyspace;
-- Show current keyspace-- (shown in prompt: cqlsh:my_keyspace>)
-- Describe commandsDESCRIBE KEYSPACES;DESC KEYSPACES; -- Abbreviation
DESCRIBE KEYSPACE my_keyspace;DESCRIBE TABLES;DESCRIBE TABLE users;DESCRIBE TYPES;DESCRIBE FUNCTIONS;DESCRIBE AGGREGATES;DESCRIBE CLUSTER;
-- Full schemaDESCRIBE SCHEMA;DESC FULL SCHEMA; -- With internalsExecution Control
Section titled “Execution Control”-- Enable/disable tracingTRACING ON;TRACING OFF;
-- Set consistency levelCONSISTENCY; -- Show currentCONSISTENCY QUORUM;CONSISTENCY LOCAL_QUORUM;
-- Serial consistency (for LWT)SERIAL CONSISTENCY LOCAL_SERIAL;
-- Expand output (vertical format)EXPAND ON;EXPAND OFF;
-- PagingPAGING ON;PAGING OFF;PAGING 100; -- Set page sizeInput/Output Commands
Section titled “Input/Output Commands”-- Capture output to fileCAPTURE '/path/to/output.txt';CAPTURE OFF;
-- Source commands from fileSOURCE '/path/to/commands.cql';
-- Login (change user)LOGIN username 'password';
-- ExitEXIT;QUIT;Query Formatting
Section titled “Query Formatting”Output Formats
Section titled “Output Formats”-- Standard outputSELECT * FROM users;
-- Expanded output (vertical)EXPAND ON;SELECT * FROM users LIMIT 1;
-- JSON outputSELECT JSON * FROM users LIMIT 1;Column Display
Section titled “Column Display”-- Select specific columnsSELECT user_id, username FROM users;
-- With functionsSELECT user_id, TTL(email), WRITETIME(email) FROM users;COPY Command
Section titled “COPY Command”Export Data (COPY TO)
Section titled “Export Data (COPY TO)”-- Export to CSVCOPY my_keyspace.users TO '/path/to/users.csv';
-- With headerCOPY my_keyspace.users TO '/path/to/users.csv' WITH HEADER = TRUE;
-- Specific columnsCOPY my_keyspace.users (user_id, username, email) TO '/path/to/users.csv';
-- With optionsCOPY my_keyspace.users TO '/path/to/users.csv'WITH HEADER = TRUE AND DELIMITER = '|' AND NULL = 'N/A' AND ENCODING = 'UTF8';Import Data (COPY FROM)
Section titled “Import Data (COPY FROM)”-- Import from CSVCOPY my_keyspace.users FROM '/path/to/users.csv';
-- With header (skip first row)COPY my_keyspace.users FROM '/path/to/users.csv' WITH HEADER = TRUE;
-- Import specific columnsCOPY my_keyspace.users (user_id, username, email) FROM '/path/to/users.csv';
-- With optionsCOPY my_keyspace.users FROM '/path/to/users.csv'WITH HEADER = TRUE AND DELIMITER = ',' AND NULL = '' AND MAXBATCHSIZE = 20 AND INGESTRATE = 10000;COPY Options
Section titled “COPY Options”| Option | Description | Default |
|---|---|---|
DELIMITER | Column delimiter | , |
QUOTE | Quote character | " |
ESCAPE | Escape character | \ |
HEADER | First row is header | FALSE |
NULL | NULL representation | empty |
ENCODING | File encoding | UTF8 |
MAXBATCHSIZE | Batch size | 20 |
INGESTRATE | Rows per second | 100000 |
CHUNKSIZE | Chunk size | 5000 |
MAXROWS | Max rows to import | -1 (all) |
Working with Data Types
Section titled “Working with Data Types”-- Generate UUIDINSERT INTO users (user_id, name) VALUES (uuid(), 'John');
-- Generate TimeUUIDINSERT INTO events (event_id, data) VALUES (now(), 'event');
-- Query with UUIDSELECT * FROM users WHERE user_id = 550e8400-e29b-41d4-a716-446655440000;Timestamps
Section titled “Timestamps”-- Insert timestampINSERT INTO events (id, created_at) VALUES (uuid(), '2024-01-15 10:30:00');
-- With timezoneINSERT INTO events (id, created_at) VALUES (uuid(), '2024-01-15 10:30:00+0000');
-- Current timestampINSERT INTO events (id, created_at) VALUES (uuid(), toTimestamp(now()));Collections
Section titled “Collections”-- ListINSERT INTO users (id, phones) VALUES (uuid(), ['+1-555-0100', '+1-555-0101']);UPDATE users SET phones = phones + ['+1-555-0102'] WHERE id = ?;
-- SetINSERT INTO users (id, tags) VALUES (uuid(), {'premium', 'verified'});UPDATE users SET tags = tags + {'new_tag'} WHERE id = ?;
-- MapINSERT INTO users (id, prefs) VALUES (uuid(), {'theme': 'dark', 'lang': 'en'});UPDATE users SET prefs['theme'] = 'light' WHERE id = ?;User-Defined Types
Section titled “User-Defined Types”-- Create typeCREATE TYPE address ( street TEXT, city TEXT, postal_code TEXT);
-- Use in tableCREATE TABLE users ( id UUID PRIMARY KEY, name TEXT, home_address FROZEN<address>);
-- Insert UDTINSERT INTO users (id, name, home_address)VALUES (uuid(), 'John', {street: '123 Main St', city: 'NYC', postal_code: '10001'});
-- Access UDT fieldsSELECT name, home_address.city FROM users;Scripting with cqlsh
Section titled “Scripting with cqlsh”Script File Example
Section titled “Script File Example”-- setup.cql
-- Create keyspaceCREATE KEYSPACE IF NOT EXISTS my_app WITH replication = { 'class': 'NetworkTopologyStrategy', 'datacenter1': 3};
USE my_app;
-- Create tablesCREATE TABLE IF NOT EXISTS users ( user_id UUID PRIMARY KEY, username TEXT, email TEXT, created_at TIMESTAMP);
CREATE TABLE IF NOT EXISTS events ( user_id UUID, event_time TIMESTAMP, event_type TEXT, data TEXT, PRIMARY KEY ((user_id), event_time)) WITH CLUSTERING ORDER BY (event_time DESC);
-- Create indexesCREATE INDEX IF NOT EXISTS ON users (email);
-- Insert sample dataINSERT INTO users (user_id, username, email, created_at)VALUES (uuid(), 'admin', 'admin@example.com', toTimestamp(now()));Running Scripts
Section titled “Running Scripts”# Execute scriptcqlsh -f setup.cql
# With authenticationcqlsh -u admin -p password -f setup.cql
# Execute inlinecqlsh -e "USE my_app; SELECT * FROM users;"
# Pipe commandsecho "SELECT * FROM system.local;" | cqlshConditional Logic (Shell)
Section titled “Conditional Logic (Shell)”#!/bin/bash# Check if keyspace existsresult=$(cqlsh -e "DESCRIBE KEYSPACE my_app" 2>&1)
if [[ $result == *"not found"* ]]; then echo "Creating keyspace..." cqlsh -f create_keyspace.cqlelse echo "Keyspace exists"fiTroubleshooting
Section titled “Troubleshooting”Connection Issues
Section titled “Connection Issues”# Test basic connectivitync -zv 10.0.0.1 9042
# Check with debugcqlsh --debug 10.0.0.1
# Check SSL issuesopenssl s_client -connect 10.0.0.1:9042Common Errors
Section titled “Common Errors”| Error | Cause | Solution |
|---|---|---|
Connection refused | Cassandra not running or wrong port | Check service, verify port |
Authentication failed | Wrong credentials | Check username/password |
SSL handshake failed | Certificate issues | Check cert paths, validate certs |
Request timed out | Query too slow | Increase timeout, optimize query |
No host available | All nodes down | Check cluster status |
Performance Issues
Section titled “Performance Issues”-- Enable tracing to diagnose slow queriesTRACING ON;SELECT * FROM large_table WHERE id = ?;
-- Check consistency level impactCONSISTENCY LOCAL_ONE; -- FasterCONSISTENCY QUORUM; -- Slower but consistentTips and Best Practices
Section titled “Tips and Best Practices”Efficiency
Section titled “Efficiency”# Use keyspace flag instead of USE commandcqlsh -k my_keyspace
# Execute multiple commands from filecqlsh -f batch_operations.cql
# Increase timeout for large operationscqlsh --request-timeout=300Security
Section titled “Security”# Don't pass password on command line (visible in history)# Bad:cqlsh -u admin -p password
# Good:cqlsh -u admin # Prompts for password
# Or use cqlshrc# ~/.cassandra/cqlshrc with restricted permissionschmod 600 ~/.cassandra/cqlshrcData Operations
Section titled “Data Operations”-- Use COPY for bulk operations, not individual INSERTs-- Good:COPY users FROM 'users.csv';
-- Less efficient for bulk:INSERT INTO users ...;INSERT INTO users ...;-- (thousands of times)
-- Limit results during explorationSELECT * FROM users LIMIT 10;Next Steps
Section titled “Next Steps”- CQLAI - Modern CQL shell with AI
- CQL Reference - CQL language guide
- nodetool Reference - Administration tool
- Data Modeling - Query design