Junior — Middle
Can you explain what a transaction is in the PostgreSQL database management system?
sobes.tech AI
Answer from AI
In PostgreSQL, a transaction is a sequence of operations with the database that are executed as a single unit. A transaction guarantees that either all operations within it are successfully completed, or none of them affect the data (atomicity). This is important for maintaining data integrity.
Transactions provide the ACID properties:
- Atomicity — all operations within a transaction are either fully completed or not executed at all.
- Consistency — after a transaction, the database remains in a correct state.
- Isolation — concurrent transactions do not interfere with each other.
- Durability — after a transaction is committed, changes are saved even in case of failures.
Example of using a transaction in Go with PostgreSQL:
import (
"database/sql"
_ "github.com/lib/pq"
)
func example(db *sql.DB) error {
tx, err := db.Begin()
if err != nil {
return err
}
_, err = tx.Exec("INSERT INTO users(name) VALUES($1)", "Alice")
if err != nil {
tx.Rollback()
return err
}
_, err = tx.Exec("UPDATE accounts SET balance = balance - 100 WHERE user_id = $1", 1)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
In this example, both operations either execute together or are not applied at all.