capypad
0 day streak
sql / expert
Snippet

Enforcing Serializability in Concurrent Transactions

The SERIALIZABLE isolation level is the highest level defined by the ANSI SQL standard. It ensures that the result of concurrent transactions is equivalent to some serial execution, preventing anomalies like phantom reads, non-repeatable reads, and write skew.

snippet.sql
sql
1
2
3
4
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
UPDATE accounts SET balance = balance - 1000 WHERE id = 1;
UPDATE accounts SET balance = balance + 1000 WHERE id = 2;
COMMIT;
Breakdown
1
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
Sets the strictest consistency constraints for the current transaction scope.
2
COMMIT
Finalizes the atomic unit of work, ensuring all changes are persisted only if no serialization conflicts occurred.