BEGIN

Name

BEGIN  --  Starts a chained-mode transaction block.

Synopsis

BEGIN [ WORK | TRANSACTION ]
  

Parameters

WORK, TRANSACTION

Both of these keywords are optional and not needed to use the command. They should be ignored.

Results

BEGIN

This message is printed if the transaction begins correctly.

NOTICE: BEGIN: already a transaction in progress

This message indicates that a transaction is already in progress. The transaction in progress is not altered or canceled when this happens.

Description

PostgreSQL executes transactions in unchained mode by default. Also termed autocommit, this mode encapsulates each user statement in a transaction and automatically finalizes the transaction by either committing the modification or performing a rollback, depending on whether or not the execution was successful.

Using BEGIN specifies that you want to enter a transaction using chained mode, in which statements will be queued by the database and then sent in a single transaction when the database receives a COMMIT,ROLLBACK, or execution abort.

Chained mode can be useful when you are working with multiple related tables, and also to increase database performance in general. Executing statements in chained mode uses less CPU and disk resources, as there is only one commit per block of statements needed.

Normally, queries inside a transaction are only aware of changes that were committed before execution of the query. This is known as a READ COMMITTED transaction isolation level. Because you will be running in chained mode, you will most likely want to set your transaction isolation level to a higher level of awareness than just queries. To do this you should use the SERIALIZABLE state; this way queries are only aware of changes that were made before the transaction. The reason this is helpful is (as has been mentioned) individual statements are no longer set within transactions, so the transactions are going to be comprised of larger blocks of code. To change your transaction isolation level to a more appropriate level, issue the command: SET TRANSACTION ISOLATION LEVEL SERIALIZABLE.

When the transaction is committed, the database will attempt to run all updates that have been specified within it. If there are were no errors, the updates will be performed; otherwise the transaction block will be aborted.

Examples

To begin and commit a transaction block:

booktown=# BEGIN WORK;
BEGIN
booktown=# CREATE TABLE test (id integer, name text);
CREATE
booktown=# COMMIT WORK;
COMMIT