Transaction isolation and concurrent updates

PostgreSQL 19.0

The previous lesson used one session to see what happens when changes are rolled back. With two sessions connected, we can see what one transaction reads while the other changes the data. Choose what a transaction can see while other transactions read or change the same database.

On this page

Create the course seats example

Complete Setup first, then connect two psql sessions to learning_db. Run this once in Session A before starting the transaction below. It sets the demo course to 10 open seats. Running it again resets the demo.

CREATE TABLE IF NOT EXISTS course_seats_demo (
  course_id integer PRIMARY KEY REFERENCES courses(id),
  seats_open integer NOT NULL CHECK (seats_open >= 0)
);

INSERT INTO course_seats_demo (course_id, seats_open)
VALUES (1, 10)
ON CONFLICT (course_id) DO UPDATE SET seats_open = EXCLUDED.seats_open;

Session A · Start Repeatable Read

Read Committed is the PostgreSQL default and takes a fresh snapshot for each statement. Repeatable Read keeps the snapshot established by the first query or data-modification statement. Run the following in Session A. It reads 10. Keep the transaction open and switch to Session B.

BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT seats_open FROM course_seats_demo WHERE course_id = 1;

Session B · Change the number of seats

Run this in Session B and commit there. The new value is 15. Switch back to Session A when COMMIT succeeds.

BEGIN;
UPDATE course_seats_demo SET seats_open = 15 WHERE course_id = 1;
COMMIT;

Session A · Compare before and after COMMIT

The first SELECT still returns 10 because Session A is reading its original snapshot. The SELECT after COMMIT returns 15.

SELECT seats_open FROM course_seats_demo WHERE course_id = 1;
COMMIT;
SELECT seats_open FROM course_seats_demo WHERE course_id = 1;

Reserve two seats in one statement

The update reserves two seats only when two or more seats are available. Check RETURNING for the new total. Zero rows means no matching course has enough open seats. In the browser this example starts independently with 10 seats.

UPDATE course_seats_demo
SET seats_open = seats_open - 2
WHERE course_id = 1 AND seats_open >= 2
RETURNING course_id, seats_open;

Choose stricter isolation when needed

Serializable checks that successfully committed transactions behave as if they ran in some serial order. If a transaction fails with SQLSTATE 40001, roll it back and retry from the beginning. PostgreSQL treats Read Uncommitted as Read Committed.

BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;

UPDATE course_seats_demo
SET seats_open = seats_open - 1
WHERE course_id = 1 AND seats_open > 0
RETURNING seats_open;

COMMIT;
-- On SQLSTATE 40001, roll back and retry the whole transaction.

Official references