A (Very) Short Introduction to Transaction Processing

You might have noticed two new commands in this example. The BEGIN WORK and ROLLBACK commands are used for transaction processing. A transaction is a group of commands. Usually, a transaction includes one or more table modifications (INSERTs, DELETEs, and UPDATEs).

BEGIN WORK marks the beginning of a transaction. Inside of a transaction, any changes that you make to the database are temporary changes. There are two ways to mark the end of a transaction: COMMIT and ROLLBACK. If you COMMIT a transaction, you are telling PostgreSQL to write all the changes made within the transaction into the database?in other words, when you COMMIT a transaction, the changes become permanent. When you ROLLBACK a transaction, all changes made within the transaction are discarded.

You can see that transactions are handy in that you can discard your changes if you change your mind. But transactions are important for another reason. PostgreSQL guarantees that all the modifications in a transaction will complete, or none of them will complete. The classic example of the importance of this property is to pretend that you are transferring money from one bank account to another. This transaction might be written in two steps. The first step is to subtract an amount from the first account. The second step is to add the amount to the second account. Now consider what would happen if your system crashed after completing the first step, but before the second step. Somehow, you've lost money! If you wrap these steps in a transaction, PostgreSQL promises that the first step will be rolled back if the second step fails (actually, the transaction will be rolled back unless you perform a COMMIT).

I'll cover the transaction processing features of PostgreSQL in great detail in Chapter 3.

    Part II: Programming with PostgreSQL