4.7 Options That Control How a Transaction Behaves

The BEGIN, COMMIT, ROLLBACK, and SAVEPOINT statements seen so far control the life cycle of a transaction. Databases also provide several options that determine how a transaction behaves. Transactions run successfully with the database defaults alone, but understanding the principles and setting these options as the situation requires can prevent unintended concurrency problems and guard against developer mistakes.

READ ONLY: read-only transactions

BEGIN READ ONLY;              -- PostgreSQL
START TRANSACTION READ ONLY;  -- MySQL
SET TRANSACTION READ ONLY;    -- Oracle (as the first statement of the transaction)

A transaction that only reads can tell the database so in advance using the READ ONLY clause. Running INSERT, UPDATE, or DELETE inside a read-only transaction raises an error. The most direct effect is preventing mistakes: the database itself stops a developer from updating or removing data in a session that only allows reads.

There is a more important effect beyond preventing mistakes. The database learns in advance that this transaction will not change any records. Since there are no writes, there is no need to prepare to write Undo log, and nothing needs to be written to disk at commit time. InnoDB does not issue a transaction number to a read-only transaction and does not register it in the active transaction list (rw_trx_list), which improves performance.

Read-write transactionRead-only transaction
Transaction number (TRX_ID)Issued (monotonically increasing, periodically written to disk)Not issued (internally 0)
Active transaction list (rw_trx_list)Registered at start, removed at end (global lock)Not registered
Undo area allocationSlot assigned in a rollback segmentNone
Cost of creating other transactions' snapshotsSubject to copyingExcluded from copying

Oracle has one more meaning. At the default isolation level (READ COMMITTED), a new snapshot is created for each statement (query) in a transaction (Chapter 7), but a READ ONLY transaction keeps the snapshot from its start time until the end. In other words, even at the READ COMMITTED isolation level, a read-only transaction gets Repeatable Read. Isolation levels and concurrency are covered in more detail in later chapters.

In the read replica setups seen in Chapter 13, it is also used as a criterion for routing requests to a replica. SQL Server has no transaction-level READ ONLY declaration; instead it conveys the same read-only intent to the database server per connection through ApplicationIntent=ReadOnly.

FOR UPDATE: an option that signals an intent to update

SELECT balance FROM account WHERE id = 'hong' FOR UPDATE;

This option is the opposite in nature of READ ONLY. It reads, but tells the database in advance that an update will follow.

An ordinary query (SELECT) takes a shared lock on rows. Shared locks do not conflict with each other, so several statements can read the same row at the same time. A concurrency error can occur when you then try to update to a new value using the value you read. Between session A reading the balance, the application computing a new balance, and writing it back, another transaction can modify the same row. As a result, one session's change is overwritten by the value another session writes later and is lost (Lost Update in Section 7.1). FOR UPDATE prevents other transactions from modifying the queried records until its own transaction ends. Reading the record while the FOR UPDATE lock is held is still possible.

Figure 4-4. Timeline of sessions A and B: without and with FOR UPDATE

Without FOR UPDATE

sequenceDiagram
  participant A as Session A
  participant DB as account row hong
  participant B as Session B
  A->>DB: SELECT balance
  DB-->>A: 500,000 won
  B->>DB: SELECT balance
  DB-->>B: 500,000 won
  Note over A: Computes new balance from 500,000 won
  Note over B: Computes new balance from 500,000 won
  A->>DB: UPDATE balance = 300,000 won, then COMMIT
  B->>DB: UPDATE balance = value B computed, then COMMIT
  Note over A,B: B overwrites A's result - A's change is lost

With FOR UPDATE

sequenceDiagram
  participant A as Session A
  participant DB as account row hong
  participant B as Session B
  participant C as Session C
  Note over A,C: t1
  A->>DB: SELECT balance FOR UPDATE
  DB-->>A: 500,000 won - row lock acquired
  Note over A,C: t2
  B->>DB: SELECT balance FOR UPDATE
  Note over B: Waits until A's lock is released
  C->>DB: SELECT balance
  DB-->>C: 500,000 won - committed version, no wait
  Note over A,C: t3
  A->>DB: UPDATE balance = 300,000 won, then COMMIT
  Note over DB: Lock released
  DB-->>B: 300,000 won - wait over, B acquires the lock
  Note over A,C: t4
  C->>DB: SELECT balance
  DB-->>C: 300,000 won
  Note over B: Computes from 300,000 won, then UPDATE and COMMIT

The first diagram shows reading without FOR UPDATE. The vertical lines are session A, the hong account row, and session B, and time flows from top to bottom. A and B read the balance with ordinary SELECT at almost the same time, and both receive 500,000 won, because ordinary reads do not block each other. Each session computes a new balance in its application based on 500,000 won, and A writes 300,000 won first and commits. When B then writes the value it computed, B's calculation did not include A's change, so A's result is overwritten and disappears. This is a Lost Update.

The second diagram does the same work with SELECT ... FOR UPDATE, and t1 to t4 mark points in time. At t1, A reads the balance of 500,000 won with FOR UPDATE and takes the row lock. At t2, B also tries to read the same row with FOR UPDATE, but is blocked by A's lock and waits without a response. Session C, which sends an ordinary SELECT at the same t2, does not wait and reads the committed value of 500,000 won as is. At t3, when A updates to 300,000 won and commits, the lock is released, and only then does B's read finish and receive 300,000 won. B computes and writes based on 300,000 won, so A's change is not lost. At t4, after A has committed, C reads again and sees 300,000 won.

In the scenario that reads without FOR UPDATE, A and B each read 500,000 won and each write their own computed value, so B, writing later, overwrites A's result. In the second scenario, A took the lock while reading, so B waits at t2 until A's write is finished. Only after A commits and releases the lock does B read 300,000 won and compute the balance. The difference is the point at which B starts reading. B waits for A's commit, but session C, which only reads data with an ordinary SELECT without FOR UPDATE, does not wait in either case. An ordinary SELECT normally reads a snapshot version of the record, so at t2, while A holds the lock with FOR UPDATE, it still reads the committed 500,000, and at t4, after A commits, it reads 300,000. FOR UPDATE makes other UPDATE statements or SELECT FOR UPDATE statements wait.

DEFERRABLE: an option that defers constraint checking to commit time

ALTER TABLE department
   ADD CONSTRAINT fk_manager FOREIGN KEY (manager_id) REFERENCES employee(id)
   DEFERRABLE INITIALLY DEFERRED;

BEGIN;
SET CONSTRAINTS fk_manager DEFERRED;   -- if created as INITIALLY IMMEDIATE, defer here
INSERT INTO department ...;
INSERT INTO employee ...;
COMMIT;                                -- checked at this point

Section 4.2 explained why constraint checking is deferred to commit time. Here only how to use it is summarized. A constraint is created as one of three kinds. NOT DEFERRABLE (the default) always checks when the statement ends. DEFERRABLE INITIALLY IMMEDIATE normally checks immediately, but if you request SET CONSTRAINTS ... DEFERRED inside a transaction, it defers to commit time for that transaction only. DEFERRABLE INITIALLY DEFERRED checks at commit time by default. In practice the second is the safest, because it keeps the quick error detection of immediate checking in normal operation and defers checking only in specific transactions that insert circular references or do bulk loads.

It can be applied not only to foreign keys but also to UNIQUE. An update that swaps sequence numbers 1 and 2 in a list briefly has two 2s the moment the first statement ends, so with immediate checking it takes three updates via a temporary number. If checking is deferred, two statements are enough. However, deferred checking is not free. The database must keep track of the rows to check at commit throughout the transaction, so it uses a lot of memory in a transaction that modifies millions of rows, and while immediate checking tells you right away which statement broke the rule, with deferred checking you have to find the cause after the commit fails.

Table 4-2. Transaction option support by DBMS

OptionApplies toPostgreSQLMySQL (InnoDB)OracleSQL Server / Azure SQL
READ ONLYTransactionBEGIN READ ONLYSTART TRANSACTION READ ONLYSET TRANSACTION READ ONLY (the whole transaction uses one snapshot)None. Replaced by the connection option ApplicationIntent=ReadOnly
FOR UPDATEQuery statementFOR UPDATE, FOR SHARE, NOWAIT, SKIP LOCKEDFOR UPDATE, FOR SHARE, NOWAIT, SKIP LOCKED (8.0)FOR UPDATE, WAIT n, NOWAIT, SKIP LOCKEDHints UPDLOCK, HOLDLOCK, READPAST, NOWAIT
DEFERRABLEConstraintSupports foreign keys, UNIQUE, PK, EXCLUDE. SET CONSTRAINTSNot supportedSupports foreign keys, UNIQUE, CHECK, and others. SET CONSTRAINTSNot supported

Learn more — PostgreSQL lock modes, InnoDB gap locks and next-key locks, Oracle TM locks and TX locks, SQL Server locks and lock escalation

NOTE Syntax and support may vary by version.

The three options differ in nature but share one thing. All of them tell the database in advance "what this transaction is going to do": it will only read, it will modify this row, this rule may be checked at the end. With that information, the database behaves more lightly, more safely, or more flexibly. This is where code that uses transactions as "just BEGIN and COMMIT" differs from code that declares its intent.

TIP One-line summary. A transaction is a unit that binds multiple changes as "all or nothing", and Part 2 is about which devices keep the four promises (ACID) the database makes for transactions. The next chapter looks at the first of those devices, the log, which lets the database keep its promises even when the server goes down.