PostgreSQL – ROLLBACK PREPARED

The ROLLBACK PREPARED command is used to roll back a prepared transaction in PostgreSQL database. Prepared transactions are a feature that allows you to prepare a transaction for execution and then later commit or roll back that transaction using a unique identifier known as the transaction’s name or identifier.

Here’s the syntax for the ROLLBACK PREPARED command:

ROLLBACK PREPARED transaction_id;

where transaction_id is the unique identifier (name) of the prepared transaction you want to roll back.

To prepare a transaction for execution and generate a unique identifier, you can use the PREPARE TRANSACTION command:

PREPARE TRANSACTION transaction_id;

Once a transaction is prepared, you can later commit it using the COMMIT PREPARED command or roll it back using the ROLLBACK PREPARED command, specifying the same transaction_id used during preparation.

Here’s an example of using PREPARE TRANSACTION and ROLLBACK PREPARED:

-- Prepare a transaction with a unique identifier 'my_transaction' 
PREPARE TRANSACTION 'my_transaction'; 
-- ... Perform some operations within the prepared transaction ... 
-- Roll back the prepared transaction using its identifier 
ROLLBACK PREPARED 'my_transaction';

This example prepares a transaction with the identifier ‘my_transaction’ and later rolls it back using the same identifier.

Prepared transactions are often used in distributed systems and scenarios where you need to ensure that a series of SQL operations are either fully committed or fully rolled back as a single unit, even if there are network or system failures during the process. The ability to roll back a prepared transaction by its identifier is a way to ensure data consistency in such situations.

Similar Posts