Full answer
Setup for the example:
CREATE TABLE shifts (day date, doctor text);
INSERT INTO shifts VALUES ('2026-12-04', 'Asha'), ('2026-12-05', 'Ben');BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT count(*) FROM shifts WHERE day = '2026-12-06';PostgreSQL returns:
count
-------
0
(1 row)In a second session:
BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT count(*) FROM shifts WHERE day = '2026-12-07';Result on PostgreSQL 17:
count
-------
0
(1 row)INSERT INTO shifts VALUES ('2026-12-07', 'Chen');Result:
INSERT 0 1In a second session:
INSERT INTO shifts VALUES ('2026-12-06', 'Dev');Output:
INSERT 0 1COMMIT;PostgreSQL returns:
COMMITIn a second session:
COMMIT;Result on PostgreSQL 17:
ERROR: could not serialize access due to read/write dependencies among transactionsSELECT day, doctor FROM shifts ORDER BY day;Result:
day | doctor
------------+--------
2026-12-04 | Asha
2026-12-05 | Ben
2026-12-07 | Chen
(3 rows)Each transaction counts shifts for one day and then inserts into the day the other one read. Because both reads were sequential scans, each transaction's read covers the whole table, so each insert conflicts with the other's read. A commits first; B's commit fails with 'could not serialize access due to read/write dependencies among transactions', and only Chen's shift is stored. With an index on day, the predicate locks would cover only the index ranges read, and these two transactions would usually both succeed. SERIALIZABLE is the simplest way to rule out anomalies such as write skew, but the application must retry on SQLSTATE 40001, and tables queried in serializable transactions should have indexes that match their predicates.
CREATE TABLE shifts (day date, doctor text);
INSERT INTO shifts VALUES ('2026-12-04', 'Asha'), ('2026-12-05', 'Ben');
BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT count(*) FROM shifts WHERE day = '2026-12-06';
-- session B
BEGIN ISOLATION LEVEL SERIALIZABLE; SELECT count(*) FROM shifts WHERE day = '2026-12-07';
INSERT INTO shifts VALUES ('2026-12-07', 'Chen');
-- session B
INSERT INTO shifts VALUES ('2026-12-06', 'Dev');
COMMIT;
-- session B
COMMIT;
SELECT day, doctor FROM shifts ORDER BY day;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- SSI tracks read/write dependencies
- Sequential scans lock the whole relation as read
- Errors can come at COMMIT
- Indexes narrow predicate locks
- Always retry 40001
Common mistakes
- Assuming different rows can never conflict
- Running SERIALIZABLE without retry logic
Follow-ups
- How does READ ONLY DEFERRABLE help reports?
- What does max_pred_locks_per_transaction control?
Tips
- Explain the table-level read lock