Sobes.tech
Senior

What are transactions and what mechanisms ensure them in PostgreSQL? Tell about the isolation levels.

sobes.tech AI

Answer from AI

A transaction is a sequence of operations on a database that is executed as a single unit: either all operations complete successfully, or in case of an error, they are rolled back to maintain data integrity. In PostgreSQL, transactions are supported by the MVCC (Multi-Version Concurrency Control) mechanism, which isolates changes made by different transactions and maintains consistency.

The main properties of transactions (ACID):

  • Atomicity — all operations within a transaction are either fully completed or not executed at all.
  • Consistency — a transaction transforms the database from one correct state to another.
  • Isolation — concurrent transactions do not interfere with each other.
  • Durability — after a transaction is committed, changes are saved even in case of failures.

PostgreSQL supports four levels of transaction isolation, defined by the SQL standard:

  1. Read Uncommitted — the lowest level, allows seeing uncommitted changes from other transactions (in PostgreSQL, it effectively works as Read Committed).
  2. Read Committed (default level) — a transaction sees only the changes that were committed at the start of each individual query.
  3. Repeatable Read — a transaction sees data as it was at its start, even if other transactions commit changes later. Prevents non-repeatable reads.
  4. Serializable — the strictest level, provides full transaction isolation as if transactions were executed sequentially.

Example of setting the isolation level in SQL:

BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- operations
COMMIT;