Sub topic 7
Setting the isolation level in practice
This chapter shows how to choose the isolation level for a session or a single transaction in PostgreSQL, MySQL and SQL Server. It also covers how to check the level you are actually running at. It assumes you know basic SQL, can use BEGIN, COMMIT and ROLLBACK, and have met the four standard levels (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE) in the previous chapter.
Three places to set a level
An isolation level can be set at three scopes. The narrower scope wins.
- Server or database default. Every new connection starts here unless something overrides it.
- Session. All later transactions on one connection use the level.
- Transaction. Only one transaction uses the level.
Setting the level per transaction is usually the safest choice. A connection pool hands the same connection to many requests, so a session-level setting can leak from one request into the next. A per-transaction setting cannot.
| Engine | Default level | Per transaction | Per session |
|---|---|---|---|
| PostgreSQL | READ COMMITTED | `BEGIN ISOLATION LEVEL ...` | `SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ...` |
| MySQL (InnoDB) | REPEATABLE READ | `SET TRANSACTION ISOLATION LEVEL ...` before `START TRANSACTION` | `SET SESSION TRANSACTION ISOLATION LEVEL ...` |
| SQL Server | READ COMMITTED | `SET TRANSACTION ISOLATION LEVEL ...` before `BEGIN TRANSACTION` | Same statement, which lasts until changed or the connection is reset |
PostgreSQL
In PostgreSQL the level is part of the BEGIN statement.
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1;
-- ... more statements ...
COMMIT;You can also start the transaction first and then set the level, but only before the first query runs.
BEGIN;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM accounts;
COMMIT;If you run SET TRANSACTION ISOLATION LEVEL after a query has already executed, PostgreSQL raises an error: SET TRANSACTION ISOLATION LEVEL must be called before any query. The snapshot is taken at the first query, so the level cannot change afterwards.
To change the default for a session, or for a database or role, use these statements:
-- All later transactions on this connection
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- Default for new connections to one database
ALTER DATABASE shop SET default_transaction_isolation = 'repeatable read';PostgreSQL accepts all four standard names, but it only implements three distinct behaviors. READ UNCOMMITTED behaves exactly like READ COMMITTED, so dirty reads never happen in PostgreSQL.
MySQL (InnoDB)
MySQL sets the level with a separate statement. Without a scope keyword, SET TRANSACTION applies only to the next transaction in the session.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;
SELECT balance FROM accounts WHERE id = 1;
COMMIT;The scope keyword changes how long the setting lasts:
-- Next transaction only (the default when no keyword is given)
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- Every later transaction on this connection
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- New connections made after this statement (needs privileges)
SET GLOBAL TRANSACTION ISOLATION LEVEL READ COMMITTED;SET TRANSACTION cannot be issued while a transaction is already open. MySQL rejects it with an error. The SET SESSION and SET GLOBAL forms do not affect the transaction in progress either.
To make a level the server default, set transaction_isolation in the configuration file:
-- my.cnf, in the [mysqld] section:
-- transaction-isolation = READ-COMMITTEDSQL Server
SQL Server sets the level with SET TRANSACTION ISOLATION LEVEL, and the setting stays in effect for the connection until you change it.
SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
BEGIN TRANSACTION;
SELECT balance FROM accounts WHERE id = 1;
COMMIT;This is a difference from MySQL and PostgreSQL, where the per-transaction form resets. In SQL Server, a pooled connection can carry the level forward to the next user of that connection. Some drivers reset the level when a connection returns to the pool, but you should not rely on that. Set the level explicitly at the start of every transaction.
SQL Server adds levels that the standard does not have:
SNAPSHOTgives snapshot isolation. It must first be enabled for the database withALTER DATABASE shop SET ALLOW_SNAPSHOT_ISOLATION ON;.READ COMMITTED SNAPSHOTis not a separateSEToption. It is a database setting (ALTER DATABASE shop SET READ_COMMITTED_SNAPSHOT ON;) that makes the ordinary READ COMMITTED level use row versions instead of shared locks.
Oracle
Oracle supports READ COMMITTED (the default) and SERIALIZABLE, plus a READ ONLY transaction mode. Its SERIALIZABLE is snapshot isolation, not full serializability. The statements look like this:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- ... statements ...
COMMIT;In Oracle, SET TRANSACTION must be the first statement of the transaction. It applies only to that transaction. To change the session default, use ALTER SESSION SET ISOLATION_LEVEL = SERIALIZABLE;.
Checking the current level
Never assume the level. Ask the database.
-- PostgreSQL
SHOW transaction_isolation;
-- MySQL 8.0 and later (older 5.7 releases use @@tx_isolation)
SELECT @@transaction_isolation;
-- SQL Server
DBCC USEROPTIONS;
-- or, for the current session:
SELECT transaction_isolation_level
FROM sys.dm_exec_sessions
WHERE session_id = @@SPID;In PostgreSQL, SHOW transaction_isolation inside an open transaction reports the level of that transaction. Outside a transaction, it reports the session default. In SQL Server, the numeric transaction_isolation_level value maps as follows:
| Value | Level |
|---|---|
| 0 | Unspecified |
| 1 | READ UNCOMMITTED |
| 2 | READ COMMITTED |
| 3 | REPEATABLE READ |
| 4 | SERIALIZABLE |
| 5 | SNAPSHOT |
Seeing the setting change the result
The same schedule gives different results depending on the level. This is the example used throughout the tutorial.
-- Setup: CREATE TABLE accounts (id int PRIMARY KEY, balance int);
-- INSERT INTO accounts VALUES (1, 100);
-- Session A (READ COMMITTED, the PostgreSQL default)
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- returns 100
-- Session B
BEGIN;
UPDATE accounts SET balance = 50 WHERE id = 1;
COMMIT;
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- returns 50: a non-repeatable read
COMMIT;
-- Repeat with BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ in Session A:
-- the second SELECT still returns 100.Only the first line of Session A changed, yet the result differs. The level is a property of the reading transaction. Session B ran at the default level in both runs.
Common mistakes
- Setting the level too late. In PostgreSQL, the level must be set before the first query of the transaction. In MySQL,
SET TRANSACTIONmust come beforeSTART TRANSACTION. - Expecting
SET TRANSACTIONto persist. In MySQL and PostgreSQL it covers one transaction. Use theSESSIONform if you want it to last. - Trusting the name. The same name means different things in different engines. REPEATABLE READ in PostgreSQL is snapshot isolation. In MySQL it is a snapshot for plain reads but not for locking reads or writes. Later chapters cover this in detail.
- Leaking levels through a connection pool. Set the level on every transaction, or reset it when you return the connection.
- Raising the level without handling failures. SERIALIZABLE and REPEATABLE READ in PostgreSQL can abort a transaction with SQLSTATE 40001. The application must retry, as a later chapter explains.
Setting the level from application code
Most drivers let you pass the level when you open a transaction. Here is a PostgreSQL example using psycopg 3, which also checks the level that is in effect.
import psycopg
with psycopg.connect("dbname=shop") as conn:
conn.isolation_level = psycopg.IsolationLevel.REPEATABLE_READ
with conn.transaction():
level = conn.execute("SHOW transaction_isolation").fetchone()[0]
print(level) # repeatable read
row = conn.execute(
"SELECT balance FROM accounts WHERE id = %s", (1,)
).fetchone()
print(row[0])Here conn.isolation_level is applied to each transaction the connection starts, so it behaves like a session setting. Reset it, or set it again, if the same connection is reused for other work.
Exercise
In MySQL you run SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;, then START TRANSACTION; ... COMMIT;, then start a second transaction with START TRANSACTION;. Which level does the second transaction use, and what would you change to make every later transaction on the connection use SERIALIZABLE?
Show answer
The second transaction uses the session default (REPEATABLE READ unless changed), because SET TRANSACTION without a scope keyword applies only to the next transaction. Use SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE; to make it last for the connection.
Exercise
A PostgreSQL transaction runs BEGIN; SELECT 1; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;. What happens, and how do you fix the code?
Show answer
PostgreSQL raises an error because the level cannot change after the first query has run. Move the level into the start of the transaction, for example BEGIN ISOLATION LEVEL SERIALIZABLE;, or issue SET TRANSACTION immediately after BEGIN and before any query.