PostgreSQL/Transactions

All data-changing operations like,  , or   must run within a surrounding construct which is called a TRANSACTION. Transactions are created with the SQL command  and finished with either   or. During the lifetime of the transaction the changes to the database are written only preliminarily. At the end,  finishes the transaction regularily and commits all intended data changes, or   aborts the transaction and reverts all those preliminary changes.

In addition to this explicit usage of SQL keywords to manage transactions, some of PostgreSQL's client libraries create implicitly a new transaction if one of the data-changing operations doesn't run in an explicitly created transaction. In this case, the operation is automatically committed immediately after its execution.


 * Hint: When working within a procedure or function, there is a  construct to define 'blocks'. In this context the meaning of   (no semikolon after BEGIN!) differs from what is explained here. You can avoid the ambiguity by using the keywords   as an alternative for   in the context of transactions. Besides that,   conforms to the SQL standard.

Transactions generate a great relief for applications. Especially for business logic that must execute many statements as a consistent unit - like the above money transfer from one bank account to another -, there is no need to take individual actions after an error occurred in the middle of a transaction. In many cases it's enough to restart the transaction or to handle errors in a unified way.

Transactions in PostgreSQL guarantee that all requirements of the ACID paradigm are fulfilled, see next chapter.

Sub-Transactions
Within a transaction the keyword  defines and denotes a position, to which the transaction may be rolled-back.