BEGIN statement initiates a transaction, which either successfully executes all of the statements it contains or none at all.
When running under the default
SERIALIZABLE isolation level, your application should use a retry loop to handle transaction retry errors that can occur under contention.Required privileges
No privileges are required to initiate a transaction. However, privileges are required for each statement within a transaction.Syntax
Aliases
In CockroachDB, the following are aliases for theBEGIN statement:
BEGIN TRANSACTIONSTART TRANSACTION
Parameters
If you do not want the transaction to run with
NORMAL priority, you can set it to LOW or HIGH.Transactions with higher priority are less likely to need to be retried.Default: NORMALSet the transaction access mode to
READ ONLY or READ WRITE. The current transaction access mode is also exposed as the session variable transaction_read_only.Default: READ WRITEExecute the transaction using the database contents “as of” a specified time in the past.The
AS OF SYSTEM TIME clause can be used only when the transaction is read-only. If the transaction contains any writes, or if the READ WRITE mode is specified, an error will be returned.Set the transaction isolation level. Transactions use
SERIALIZABLE isolation by default. They can be configured to run at READ COMMITTED isolation.This clause is supported for compatibility with PostgreSQL.
NOT DEFERRABLE is a no-op and the default behavior for CockroachDB. DEFERRABLE returns an unimplemented error.Examples
Begin a transaction with default settings
Without modifying theBEGIN statement, the transaction uses SERIALIZABLE isolation and NORMAL priority.
Change isolation level
You can set the transaction isolation level toSERIALIZABLE or READ COMMITTED.
If not specified, transactions use the value of the current session’s default_transaction_isolation variable.
Change priority
You can set a transaction’s priority toLOW or HIGH.
SET TRANSACTION.
Use the AS OF SYSTEM TIME option
You can execute the transaction using the database contents “as of” a specified time in the past.You can also use the
SET TRANSACTION statement inside the transaction to achieve the same results.Begin a transaction with automatic retries
CockroachDB will automatically retry all transactions that contain bothBEGIN and COMMIT in the same batch. Batching is controlled by your driver or client’s behavior.
From the perspective of CockroachDB, a transaction sent as a batch looks like this:
See also
- COMMIT
- SAVEPOINT
- RELEASE SAVEPOINT
- ROLLBACK
- Transactions