Understanding Isolation Levels
1. Understanding Read Committed
| Property | Detail |
| Default | Yes |
| Sees | Snapshot at start of each statement |
| Prevents | Dirty reads |
| Allows | Non-repeatable reads, phantoms |
2. Understanding Repeatable Read
| Property | Detail |
| Sees | Snapshot at first statement of TX |
| Prevents | Dirty + non-repeatable reads + phantoms (PG-specific) |
| Conflicts | Raises serialization_failure (40001) on concurrent updates |
3. Understanding Serializable
BEGIN ISOLATION LEVEL SERIALIZABLE;
-- SSI: predicate locks detect conflicts
COMMIT; -- may raise 40001 — retry
| Implementation | SSI (Serializable Snapshot Isolation) |
| Prevents | All anomalies |
| Cost | Predicate locks + retry logic required |
4. Setting Transaction Isolation Level
BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- or
BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE;
5. Setting Default Isolation Level
ALTER DATABASE shop SET default_transaction_isolation = 'repeatable read';
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL SERIALIZABLE;
6. Understanding Read Phenomena
| Phenomenon | RC | RR | S |
| Dirty read | No | No | No |
| Non-repeatable | Yes | No | No |
| Phantom | Yes | No (PG) | No |
| Serialization anomaly | Yes | Yes | No |
7. Handling Serialization Failures
-- Pseudocode retry loop
for attempt in 1..5 loop
BEGIN ISOLATION LEVEL SERIALIZABLE;
... ;
COMMIT; -- on 40001 retry
end loop;
Warning: Application MUST retry on SQLSTATE 40001 / 40P01 — server cannot transparently retry.
8. Using READ ONLY Transactions
BEGIN READ ONLY; -- forbids writes; allows planner optimizations
SELECT ... ;
COMMIT;
9. Using READ WRITE Transactions
BEGIN READ WRITE; -- default mode
10. Understanding MVCC
| Concept | Detail |
| Tuple visibility | xmin / xmax + snapshot |
| Writers | Never block readers |
| Readers | Never block writers |
| Garbage | VACUUM reclaims dead tuples |