The ROLLBACK command undoes all database updates made during the current transaction, and ends the current transaction.
The ROLLBACK command may be used within anonymous blocks, stored procedures, or functions. Within an SPL program, it may appear in the executable section and/or the exception section.
In the following example, the exception section contains a ROLLBACK command. Even though the first two INSERT commands are executed successfully, the third results in an exception that results in the rollback of all the INSERT commands in the anonymous block.
The following is a more complex example using both COMMIT and ROLLBACK. First, the following stored procedure is created which inserts a new employee.
Note that this procedure has no exception section so any error that may occur is propagated up to the calling program.
The following anonymous block is run. Note the use of the COMMIT command after all calls to the emp_insert procedure and the ROLLBACK command in the exception section.
The following SELECT command shows that employees Farrell and Tyler were successfully added.
Now, execute the following anonymous block:
A SELECT command run against the table yields the following:
The ROLLBACK command in the exception section successfully undoes the insert of employee Harrison. Also note that employees Farrell and Tyler are still in the table as their inserts were made permanent by the COMMIT command in the first anonymous block.
Note
Executing a COMMIT or ROLLBACK in a plpgsql procedure will throw an error if there is an Oracle-style SPL procedure on the runtime stack.