Sub topic 9
Read consistency and isolation levels
This chapter assumes you know how COMMIT and ROLLBACK work and that Oracle keeps undo data for open transactions. You also need to be able to run two SQL sessions side by side, for example two SQL Developer worksheets or two SQLcl windows. The examples use the accounts table from earlier chapters.
What read consistency guarantees
Oracle guarantees that a query sees data as it existed at a single point in time, and that it never sees uncommitted changes from other sessions. That point in time is identified by a system change number (SCN). The SCN is a counter that Oracle increments as the database commits changes.
When a query starts, Oracle records the current SCN. While the query reads blocks, it checks each block for changes made after that SCN. If it finds one, it rebuilds the older version of the data from undo and returns that version. Readers therefore do not take locks on the rows they read, and they are not blocked by writers.
This gives three properties:
- No dirty reads. A session never sees another session's uncommitted data.
- Statement-level consistency. One query returns results from one moment, even if it runs for an hour while others commit changes.
- Readers and writers do not block each other. A SELECT never waits for an UPDATE, and an UPDATE never waits for a SELECT.
Oracle does not offer READ UNCOMMITTED. It also has no REPEATABLE READ level under that name.
The three transaction modes
Oracle supports three modes. They differ in the point in time that a query uses as its snapshot.
| Mode | Snapshot taken | Can modify data | Typical use |
|---|---|---|---|
| READ COMMITTED (default) | At the start of each statement | Yes | Most OLTP work |
| SERIALIZABLE | At the start of the transaction | Yes, with restrictions | Logic that must see one stable view and can retry |
| READ ONLY | At the start of the transaction | No | Reports that run several queries |
READ COMMITTED
This is the default. Each statement sees data committed before that statement began. Two statements in the same transaction can therefore see different data. This difference produces two anomalies that you must handle in your design:
- A non-repeatable read happens when you read a row twice and get different values, because another session committed a change in between.
- A phantom read happens when you run the same query twice and the second run returns additional or fewer rows.
Here is a non-repeatable read:
-- Session A
SELECT balance FROM accounts WHERE id = 2; -- returns 300
-- Session B
UPDATE accounts SET balance = 999 WHERE id = 2;
COMMIT;
-- Session A (same transaction)
SELECT balance FROM accounts WHERE id = 2; -- now returns 999Session A's first query is not affected by Session B's change. The second query starts after Session B committed, so it sees the new value.
Statement restarts
A DML statement in READ COMMITTED mode finds its target rows using its snapshot, but it must change the current version of each row. If another session committed a change to a target row after the statement began, Oracle rolls back the statement's work and restarts it with a new snapshot. A restart is invisible to the client, but triggers on the table may fire more than once for the same logical row. Avoid side effects in row triggers, such as sending email or writing to external files, because a restart can repeat them.
Lost updates
A common error is reading a value into your application, computing a new one, and writing it back:
-- Unsafe: another session may change the row between the read and the write
SELECT balance FROM accounts WHERE id = 1;
-- application computes new_balance = balance - 100
UPDATE accounts SET balance = :new_balance WHERE id = 1;If two sessions do this at the same time, the second write overwrites the first, and one change is lost. There are two standard fixes. First, compute the change inside the UPDATE statement, as in SET balance = balance - 100. Second, lock the row before reading it:
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;FOR UPDATE is the exception to the "readers do not block" rule. It reads the current committed version and waits if another session holds the row lock. The next chapter covers locks in detail.
SERIALIZABLE
In a serializable transaction, every query sees the data as it was when the transaction began, plus the transaction's own changes. Repeated reads return the same values, and phantoms do not appear.
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT balance FROM accounts WHERE id = 2;
-- ... other sessions commit changes to row 2 here ...
SELECT balance FROM accounts WHERE id = 2; -- same value as the first querySET TRANSACTION must be the first statement in the transaction. If you issue it after other statements, Oracle raises ORA-01453. The setting lasts until the transaction ends with COMMIT or ROLLBACK, and the next transaction returns to READ COMMITTED. To make every transaction in a session serializable, use ALTER SESSION SET ISOLATION_LEVEL = SERIALIZABLE;.
ORA-08177
A serializable transaction cannot change a row if another transaction changed and committed that row after the serializable transaction began. Oracle cannot apply your change to a version you have never seen, so it raises an error:
-- Session A
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SELECT balance FROM accounts WHERE id = 2;
-- Session B
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT;
-- Session A
UPDATE accounts SET balance = balance - 10 WHERE id = 2;
-- ORA-08177: can't serialize access for this transactionYour application must be ready to handle this error. The usual response is to roll back and run the whole transaction again. If you use SERIALIZABLE, write the retry loop. Without one, the mode causes failures under load.
Limits of Oracle's SERIALIZABLE
Oracle's implementation is snapshot isolation. It prevents the anomalies above, but it does not guarantee that the result equals some serial order of transactions. Two serializable transactions can each read rows the other writes, and then both succeed, giving a result that no serial order could produce. This is called write skew. For example, a rule such as "at least one doctor must stay on call" can be broken by two transactions that each remove a different doctor after checking the count. If you must enforce rules across rows, use constraints, or lock the rows you check with SELECT ... FOR UPDATE.
READ ONLY
A read-only transaction gives you the same transaction-level snapshot as SERIALIZABLE, but it does not allow data changes. Use it for reports that run several queries and must be consistent with each other.
SET TRANSACTION READ ONLY;
SELECT SUM(balance) FROM accounts;
SELECT COUNT(*) FROM accounts; -- consistent with the SUM above
COMMIT;An INSERT, UPDATE, or DELETE in this mode raises ORA-01456. Because it never writes, it cannot raise ORA-08177. A read-only transaction ends with COMMIT or ROLLBACK, and both do the same thing here.
When consistency fails: ORA-01555
Read consistency depends on undo data surviving long enough. If a query needs an old version of a block and the undo for it has been overwritten, Oracle cannot rebuild the block and raises ORA-01555 "snapshot too old". Long-running queries, small undo tablespaces, and a short UNDO_RETENTION setting all make this more likely. Long SERIALIZABLE and READ ONLY transactions are at higher risk, because their snapshot is held for the whole transaction.
Choosing a mode
Use these criteria:
- Use READ COMMITTED for ordinary transactions. Write DML so that it does not depend on values read earlier, or lock rows with
FOR UPDATE. - Use READ ONLY for multi-query reports. It is simple and cannot fail with ORA-08177.
- Use SERIALIZABLE when a transaction reads and then writes, needs a stable view, and can be retried. Expect ORA-08177 on busy rows.
- Keep any long transaction short. A held snapshot raises the chance of ORA-01555.
Exercise
Session A runs SET TRANSACTION ISOLATION LEVEL SERIALIZABLE and reads the balance of account 2. Session B then updates account 2 and commits. Session A reads the balance again, then tries to update account 2. What does Session A see on the second read, and what happens on the update?
Show answer
The second read returns the same value as the first, because a serializable transaction uses the snapshot taken when it began. The update fails with ORA-08177, because another transaction changed and committed the row after Session A's transaction began. Session A should roll back and retry the transaction.
Exercise
A report runs three queries against accounts while other sessions keep committing transfers. The totals from the queries must agree with each other, and the report never writes data. Which transaction mode fits, and why is it better than SERIALIZABLE here?
Show answer
Use SET TRANSACTION READ ONLY. All three queries see data as of the start of the transaction, so the totals are consistent. It also rejects any DML, so it cannot raise ORA-08177 and needs no retry logic.