Catalog / CockroachDB SQL Cheatsheet
CockroachDB SQL Cheatsheet
A quick reference guide to CockroachDB's SQL dialect, covering data definition, manipulation, querying, and transaction management. Useful for both beginners and experienced users looking to quickly recall syntax and best practices.
Data Definition Language (DDL)
Creating Databases
Syntax: Creates a new database. Example:
|
Creating a database if it does not exist: Creates a new database only if one doesn’t already exist. Example:
|
Creating Tables
Syntax: Creates a new table. Example:
|
Data Types: Common data types include Constraints: |
Creating a table with foreign key:
|
Altering Tables
Syntax: Adds a new column to an existing table. Example:
|
Syntax: Removes a column from an existing table. Example:
|
Syntax: Renames a column in an existing table. Example:
|
Data Manipulation Language (DML)
Inserting Data
Syntax: Inserts new rows into a table. Example:
|
Inserting multiple rows:
|
Inserting all columns: If inserting into all columns, you can omit the column names.
|
Updating Data
Syntax: Updates existing rows in a table. Example:
|
Updating multiple columns:
|
Deleting Data
Syntax: Deletes rows from a table. Example:
|
Deleting all rows (truncate): Use with caution!
|
Data Querying (SELECT)
Basic SELECT Statements
Syntax: Retrieves data from a table. Example:
|
Selecting all columns:
|
Using aliases:
|
Filtering and Sorting
WHERE Clause:
|
ORDER BY Clause:
|
LIMIT and OFFSET:
|
Aggregate Functions
Common functions: Example:
|
GROUP BY Clause:
|
HAVING Clause: Filters groups based on a condition.
|
Transactions
Transaction Management
Starting a transaction: Marks the beginning of a transaction block. Example:
|
Committing a transaction: Saves all changes made during the transaction. |
Rolling back a transaction: Discards all changes made during the transaction. |
Savepoints:
|
Isolation Levels
CockroachDB supports It prevents phenomena like dirty reads, non-repeatable reads, and phantom reads. |
Concurrency Control
CockroachDB uses optimistic concurrency control, which assumes that multiple transactions can frequently complete without interfering with each other. |