WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

PostgreSQL Β· Basic Β· question 10 of 100

What is a transaction and how does PostgreSQL handle transactions?

πŸ“• Buy this interview preparation book: 100 PostgreSQL questions & answers β€” PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic PostgreSQL interview β€” then scores it.
πŸ“ž Practice PostgreSQL β€” free 15 min
πŸ“• Buy this interview preparation book: 100 PostgreSQL questions & answers β€” PDF + EPUB for $5

All 100 PostgreSQL questions Β· All topics