BEGIN starts a transaction block. All statements after BEGIN execute as a single transaction until you issue an explicit COMMIT or ROLLBACK.
Without BEGIN, PolarDB PostgreSQL runs in autocommit mode: each statement executes in its own transaction and commits automatically on success, or rolls back on failure.
Why use a transaction block
Grouping statements in a transaction block offers two advantages:
Performance: Starting and committing a transaction requires significant CPU and disk activity. Batching multiple statements into one transaction reduces that overhead.
Consistency: Other sessions cannot see intermediate states. Until you commit, any partially applied changes are invisible to other connections.
If the isolation level, read/write mode, or deferrable mode is specified, the new transaction has those characteristics, as if SET TRANSACTION was executed.
Synopsis
BEGIN [ WORK | TRANSACTION ] [ transaction_mode [, ...] ]
where transaction_mode is one of:
ISOLATION LEVEL { SERIALIZABLE | REPEATABLE READ | READ COMMITTED | READ UNCOMMITTED }
READ WRITE | READ ONLY
[ NOT ] DEFERRABLEParameters
| Parameter | Description |
|---|---|
WORK | TRANSACTION | Optional keywords. They have no effect on behavior. |
ISOLATION LEVEL | Sets the transaction isolation level. Valid values: SERIALIZABLE, REPEATABLE READ, READ COMMITTED, READ UNCOMMITTED. |
READ WRITE | READ ONLY | Sets the transaction access mode. READ ONLY prevents data modifications in the transaction. |
DEFERRABLE | NOT DEFERRABLE | Controls whether a SERIALIZABLE READ ONLY transaction can be deferred to avoid blocking. Has no effect on other transaction types. |
For full details on each transaction mode, see SET TRANSACTION.
Usage notes
SET TRANSACTION has the same functionality as
BEGIN.Issuing
BEGINinside an existing transaction block triggers a warning. The current transaction state is not affected.To nest transactions within a transaction block, use savepoints. See SAVEPOINT.
For backward compatibility, you can omit commas between successive
transaction_modevalues.
Examples
Start a transaction with default settings
BEGIN;Set the isolation level
BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;Start a read-only transaction
BEGIN READ ONLY;Combine isolation level and access mode
BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE;