Description

A database transaction is a single unit of work made up of one or more SQL operations treated as one. You BEGIN, run queries, then end the transaction. PostgreSQL transactions follow the ACID principles to manage concurrent access and prevent data corruption.

When to Use Transactions

  • Financial applications (banking, e-commerce)
  • Inventory management systems
  • Reservation systems (airlines, hotels)
  • Any application where many users share data

ACID Properties

PropertyMeaning
AtomicityAll-or-nothing. If any operation fails, the entire transaction is rolled back and nothing is committed
ConsistencyThe transaction moves the database from one valid state to another, obeying all schema rules (unique keys, foreign keys, CHECK constraints)
IsolationConcurrent transactions do not interfere; each runs as if it were alone. The degree of isolation is set by the isolation level and affects which read phenomena can occur
DurabilityOnce committed, changes are permanent and survive crashes or power loss (changes are persisted to non-volatile storage)

Transaction Lifecycle

  1. Begin: start the transaction.
  2. Execute: perform reads, writes or updates.
  3. Commit: confirm and save changes if all operations succeed.
  4. Rollback: revert changes if an error occurs, keeping data integrity.

Transaction Control Statements

BEGIN;                    -- also: BEGIN TRANSACTION;  BEGIN WORK;
COMMIT;                   -- also: COMMIT TRANSACTION; COMMIT WORK;
ROLLBACK;                 -- also: ROLLBACK TRANSACTION; ROLLBACK WORK;

If an error occurs at any point, call ROLLBACK instead of COMMIT.

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob';
COMMIT;

Isolation Levels

LevelBehaviour
Read UncommittedAllows reading uncommitted changes (in PostgreSQL it behaves like Read Committed)
Read Committed (default)Only reads committed data
Repeatable ReadConsistent data for the whole transaction, even if other transactions modify it
SerializableStrictest: transactions behave as if executed one after another
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- or
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

Savepoints

A savepoint is a checkpoint inside a transaction that you can roll back to without undoing the entire transaction.

BEGIN;
INSERT INTO booking VALUES (...);
SAVEPOINT after_booking;
UPDATE flights SET status = 'full' WHERE flight_no = 'UK-KS';
ROLLBACK TO SAVEPOINT after_booking;   -- undo only the update
COMMIT;

Benefits:

  • Flexibility: partial rollbacks instead of full ones.
  • Error management: isolate and handle errors in sections, retry or skip steps.
  • Modularity: break a large transaction into parts that are easier to understand, test and debug (financial processing, booking systems).

Example: Booking a Flight

BEGIN;

SELECT status FROM flights WHERE flight_no = 'UK-KS';   -- 'available'

UPDATE flights SET status = 'full' WHERE flight_no = 'UK-KS';
INSERT INTO booking (passenger_id, flight_no) VALUES (1, 'UK-KS');   -- Zere's ticket

COMMIT;

Walkthrough: the transaction starts with BEGIN; the flight status is checked and is available; after Zere books her ticket the status is updated to full; a record for Zere is inserted into booking; COMMIT saves all changes. Cancelling a booking is done the same way: delete the booking row and set the flight status back, inside one transaction.

Advantages

  • ACID guarantees for reliable data.
  • Error handling and rollback: failures return data to its initial state, preventing corrupt or partial entries.
  • Concurrency control: isolation lets many users work at once without breaking consistency.

Disadvantages

  • Complexity and overhead: managing transactions and isolation levels complicates design and costs computation.
  • Reduced concurrency due to locking: stricter isolation may block access to data until the transaction ends.
  • Resource consumption: long or complex transactions use significant resources.
  • Harder debugging: errors can be difficult to diagnose because of dependencies between operations.

Conclusion

Transactions guarantee that groups of operations succeed or fail together, which is essential wherever data correctness matters (money, inventory, bookings).