BEGIN

Name

BEGIN  --  Begins a transaction in chained mode

Synopsis

  
BEGIN [ WORK | TRANSACTION ]
  

Inputs

WORK

Optional keyword. Has no effect.

TRANSACTION

Optional keyword. Has no effect.

Outputs

BEGIN

This signifies that a new transaction has been started.

NOTICE: BEGIN: already a transaction in progress

This indicates that a transaction was already in progress. The current transaction is not affected.

Description

By default, PostgreSQL executes transactions in unchained mode (also known as "autocommit" in other database systems). In other words, each user statement is executed in its own transaction and a commit is implicitly performed at the end of the statement (if execution was successful, otherwise a rollback is done). BEGIN initiates a user transaction in chained mode, that is, all user statements after BEGIN command will be executed in a single transaction until an explicit COMMIT, ROLLBACK, or execution abort. Statements in chained mode are executed much faster, because transaction start/commit requires significant CPU and disk activity. Execution of multiple statements inside a transaction is also required for consistency when changing several related tables.

The default transaction isolation level in PostgreSQL is READ COMMITTED, where queries inside the transaction see only changes committed before query execution. So if you need more rigorous transaction isolation, you have to use SET TRANSACTION ISOLATION LEVEL SERIALIZABLE just after BEGIN. In SERIALIZABLE mode, queries will see only changes committed before the entire transaction began (or to be precise, before execution of the first DML statement in a serializable transaction).

If the transaction is committed, PostgreSQL will ensure either that all updates are done or that none of them are done. Transactions have the standard ACID (atomic, consistent, isolatable, and durable) properties.

Notes

Use COMMIT or ROLLBACK to terminate a transaction.

Usage

To begin a user transaction
CREATE TABLE t1 (
   i1 integer
);
INSERT INTO t1 (i1) VALUES (1);
INSERT INTO t1 VALUES (2);
BEGIN;
DELETE FROM t1;
ABORT; –– to abort changes
SELECT * FROM t1;
  
Result:
 t1
---
 1
 2

Compatibility

SQL92

There is no BEGIN statement in SQL92. Transaction initiation is always implicit and it terminates either with a COMMIT or ROLLBACK statement.

Note that the BEGIN keyword is used for a different purpose in embedded SQL. You are advised to be careful about the transaction semantics when porting database applications.

SQL92 also requires SERIALIZABLE to be the default transaction isolation level.