Sobes.tech
Senior

Tell about locks and the use of transactions in PostgreSQL.

sobes.tech AI

Answer from AI

In PostgreSQL, locks are used to ensure data integrity and transaction isolation. The main types of locks:

  • Row-level locks — lock individual rows in a table, allowing other transactions to work with different rows. This minimizes contention.
  • Table-level locks — lock the entire table, used less frequently, for example, when changing the structure.

PostgreSQL uses MVCC (Multi-Version Concurrency Control), which allows transactions to read data without locks until a write occurs.

Transactions in PostgreSQL provide atomicity, consistency, isolation, and durability (ACID). Important:

  • Start a transaction with the BEGIN command or use autocommit.
  • Choose an isolation level (Read Committed, Repeatable Read, Serializable), which affects data visibility and locking.
  • Monitor transaction duration to avoid long-lasting locks.

Example of using a transaction:

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

If a lock conflict occurs during the process, one of the transactions may be rolled back with an error, which should be handled in the application.