A transaction is a logical unit of work that contains one or more database operations, such as insert, update, or delete. Transactions ensure that all database operations either complete successfully, or the entire set of operations is rolled back to its original state before the entire transaction started.
PostgreSQL supports the standard transaction properties of Atomicity, Consistency, Isolation, and Durability (ACID). This means that a transaction is a single, indivisible unit of work that is either fully executed or not at all. PostgreSQL ensures that transactions are isolated from each other, and that no transaction interferes with others, even when they access the same data concurrently.
To use transactions in PostgreSQL, you need to put your code in a transaction block. For example, in Java, the following code creates a transaction block that inserts two rows into the "my_table" table:
try (Connection conn = dataSource.getConnection()) {
conn.setAutoCommit(false); // start transaction
try (Statement stmt = conn.createStatement()) {
stmt.execute("INSERT INTO my_table (col1, col2) VALUES ('value1', 1)");
stmt.execute("INSERT INTO my_table (col1, col2) VALUES ('value2', 2)");
}
conn.commit(); // commit transaction
} catch (SQLException e) {
conn.rollback(); // rollback transaction
}
In this example, we start a transaction block by setting "auto-commit" to false. Then we execute two SQL statements that insert two rows into the "my_table" table. Finally, if there are no exceptions, we commit the transaction, or we rollback the transaction if there is an exception.
PostgreSQL also supports savepoints, which allow you to create nested transactions within a transaction. This feature is useful when you need to roll back only part of a transaction, while leaving the rest intact.
To summarize, PostgreSQL provides full support for transactions and ensures that they are isolated from each other. To use transactions in PostgreSQL, you need to put your code in a transaction block and either commit or rollback the transaction at the end, depending on the success or failure of your database operations.