0
0
PostgresqlHow-ToBeginner · 3 min read

How to Set Isolation Level in PostgreSQL: Syntax and Examples

In PostgreSQL, you set the transaction isolation level using the SET TRANSACTION ISOLATION LEVEL command inside a transaction block or with SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL for the whole session. Common isolation levels include READ COMMITTED, REPEATABLE READ, and SERIALIZABLE.
📐

Syntax

You can set the isolation level for the current transaction or for the entire session.

  • For current transaction: Use SET TRANSACTION ISOLATION LEVEL <level> inside a transaction block.
  • For session-wide setting: Use SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL <level>.
  • Isolation levels: READ UNCOMMITTED (treated as READ COMMITTED), READ COMMITTED (default), REPEATABLE READ, and SERIALIZABLE.
sql
BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- Your SQL statements here
COMMIT;
💻

Example

This example shows how to set the isolation level to SERIALIZABLE for a single transaction and then run a query.

sql
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT * FROM users WHERE id = 1;
COMMIT;
Output
id | name ----+------- 1 | Alice (1 row)
⚠️

Common Pitfalls

  • Trying to set the isolation level outside a transaction block using SET TRANSACTION causes an error.
  • Using SET TRANSACTION after executing queries in the same transaction has no effect.
  • Confusing session-level and transaction-level commands can lead to unexpected isolation behavior.
sql
/* Wrong: SET TRANSACTION outside a transaction block */
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- ERROR: SET TRANSACTION can only be used in transaction blocks

/* Correct: Use BEGIN first */
BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- Your queries
COMMIT;
📊

Quick Reference

CommandDescription
SET TRANSACTION ISOLATION LEVEL Sets isolation level for current transaction (must be inside BEGIN...COMMIT)
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL Sets isolation level for all transactions in the session
Isolation LevelsREAD UNCOMMITTED (treated as READ COMMITTED), READ COMMITTED (default), REPEATABLE READ, SERIALIZABLE

Key Takeaways

Use SET TRANSACTION ISOLATION LEVEL inside a transaction block to set isolation for that transaction.
Use SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL to set isolation for the whole session.
PostgreSQL treats READ UNCOMMITTED as READ COMMITTED internally.
Set the isolation level before running queries in the transaction to ensure it takes effect.
Confusing transaction-level and session-level commands can cause unexpected results.