skip to content

In SQLite, how do BEGIN DEFERRED, BEGIN IMMEDIATE and BEGIN EXCLUSIVE differ, and which one does a plain BEGIN use?

level: middleimportance: must knowfreq 75%

answer

  1. when the lock is taken
  2. plain BEGIN takes nothing yet
  3. write lock at BEGIN time
  4. EXCLUSIVE equals IMMEDIATE in WAL

basics

~20 s

A plain BEGIN is DEFERRED: no lock until the first read or write. BEGIN IMMEDIATE takes the write lock at once; BEGIN EXCLUSIVE also shuts out readers in rollback-journal mode, and in WAL mode behaves like IMMEDIATE.

solid answer

~50 s

The three forms differ only in when the transaction takes its locks. The default, `DEFERRED`, just turns off autocommit: the first `SELECT` starts a read transaction and the first write starts a write transaction, upgrading the read one if it can or failing with `SQLITE_BUSY` if another connection is writing or has already changed the database. `BEGIN IMMEDIATE` starts a write transaction straight away, so it can fail with `SQLITE_BUSY` at `BEGIN` itself, but once it succeeds no other connection can start writing until it ends. `BEGIN EXCLUSIVE` also starts a write transaction and, in rollback-journal mode, stops other connections reading; in WAL mode it is the same as `IMMEDIATE`. Rule of thumb: start any transaction that will write with `IMMEDIATE`, so contention shows up at `BEGIN`, where a busy timeout can wait for it.

code

sql · 8 lines
sql
CREATE TABLE IF NOT EXISTS request_log(id INTEGER PRIMARY KEY, path TEXT, status INTEGER);
CREATE TABLE IF NOT EXISTS counters(name TEXT PRIMARY KEY, hits INTEGER NOT NULL DEFAULT 0);
INSERT OR IGNORE INTO counters(name) VALUES ('requests');

BEGIN IMMEDIATE;
INSERT INTO request_log(path, status) VALUES ('/health', 200);
UPDATE counters SET hits = hits + 1 WHERE name = 'requests';
COMMIT;

go deeper

for a junior

Know that plain BEGIN means DEFERRED and takes no lock until the first statement touches the database.

for a middle

Explain the lock each form takes in rollback and WAL mode, and why IMMEDIATE moves the risk of SQLITE_BUSY to the BEGIN statement.

for a senior

Argue for BEGIN IMMEDIATE on every writing transaction in a concurrent service, and say what it costs: other writers wait from BEGIN to COMMIT, so batches stay short.

for a principal

Treat the transaction type as a team convention: decide where writing transactions start, enforce it in the data layer, and keep EXCLUSIVE for the rare rollback-mode case.

## Autocommit comes first Every read or write in SQLite happens inside a transaction. If none is open, any statement that touches the database starts one automatically, an **implicit transaction**, and commits it when the last active statement on the connection finishes. A statement is only certain to have finished once it is reset or finalized, so a `SELECT` left half-stepped keeps its implicit transaction open. `BEGIN` takes the connection out of autocommit until `COMMIT` (or its alias `END`) or `ROLLBACK`. `BEGIN` comes in three forms, and they differ in one thing: **when the transaction takes its locks**. ## DEFERRED, the default A plain `BEGIN` is `BEGIN DEFERRED`. Internally it only sets a flag that turns off the automatic commit; it takes **no lock at all**. The transaction really starts with the first statement that touches the database: - if that statement is a `SELECT`, a **read transaction** starts; - if it is a write (`INSERT`, `UPDATE`, `DELETE`, `CREATE`, `DROP`), a **write transaction** starts; - a later write inside a read transaction must **upgrade** it, which fails with `SQLITE_BUSY` if another connection is already writing or has already changed the database. Deferred keeps the database open to other connections for as long as possible, which suits read-only transactions. Its trap is the read-then-write transaction, which can fail half-way through. ## IMMEDIATE `BEGIN IMMEDIATE` starts a write transaction at once, without waiting for a write statement. Only one write transaction can exist per database, so `BEGIN IMMEDIATE` may itself return `SQLITE_BUSY` when another connection is writing. That failure comes at the start, before any work is done, at a point where the connection's busy handler can wait for the lock. Once it succeeds, no other connection can start writing until this one commits or rolls back, while readers on other connections carry on. ## EXCLUSIVE `BEGIN EXCLUSIVE` also starts a write transaction immediately. In rollback-journal mode it goes further and **prevents other connections from reading** while the transaction is under way. In WAL mode `EXCLUSIVE` and `IMMEDIATE` are the same. ## What each one takes, by journal mode | Statement | Rollback-journal mode | WAL mode | |---|---|---| | `BEGIN` / `BEGIN DEFERRED` | Nothing; `SHARED` at the first read, `RESERVED` at the first write | Nothing; a read snapshot at the first read, the write lock at the first write | | `BEGIN IMMEDIATE` | `RESERVED` at once; other connections can still read | The write lock at once; readers continue | | `BEGIN EXCLUSIVE` | `EXCLUSIVE` at once; no other connection can read | Same as `BEGIN IMMEDIATE` | In rollback mode a writer still needs `EXCLUSIVE` to write the database file itself, normally at commit, so even an `IMMEDIATE` transaction waits at `COMMIT` for the readers already inside to finish. A single write statement in autocommit mode starts from no transaction, so like `BEGIN IMMEDIATE` it can wait under the busy handler for the write lock; the risky case is a write that arrives after a read inside one deferred transaction, or after a read left open by an unfinished statement. ## Choosing one 1. **Read-only work:** a plain `BEGIN`, or no explicit transaction for a single statement. 2. **Anything that writes, above all read-then-write:** `BEGIN IMMEDIATE`, so contention appears at `BEGIN`, where the busy timeout waits, instead of in the middle, where it may not. 3. **Rollback mode, when no other connection may even read:** `BEGIN EXCLUSIVE`. It is rarely needed, and in WAL mode it buys nothing over `IMMEDIATE`. In a multi-threaded service writing request logs, each worker that inserts a batch of rows and bumps a counter should open the batch with `BEGIN IMMEDIATE`, keep it small and commit promptly: the write lock is held from `BEGIN` to `COMMIT`, and every other writer queues behind it. ## BEGIN does not nest Transactions started with `BEGIN` do not nest. Running `BEGIN` while any transaction is open fails with the error `cannot start a transaction within a transaction`, whether the open one came from `BEGIN` or from a `SAVEPOINT`. Nested units of work use named `SAVEPOINT`s instead, and an outermost `SAVEPOINT` issued outside `BEGIN` starts the transaction exactly as `BEGIN DEFERRED` would, taking no lock until the first read or write.

  • What happens if you run BEGIN while a SQLite transaction is already open, and how do you nest work instead?
    It fails with `cannot start a transaction within a transaction`, whether the open transaction came from `BEGIN` or `SAVEPOINT`. Nesting uses `SAVEPOINT name` and `RELEASE name`; an outermost `SAVEPOINT` outside `BEGIN` acts like `BEGIN DEFERRED`, and releasing it commits. Inner releases only merge work into the enclosing transaction; nothing is durable until the outermost one commits.
  • Can a SQLite transaction started with BEGIN IMMEDIATE still meet SQLITE_BUSY after BEGIN succeeds?
    Not from another writer: none can start until it ends. In rollback-journal mode, though, `COMMIT` needs `EXCLUSIVE` and must wait for current readers to drop their `SHARED` locks. The busy handler waits for them; if they outlast it, `COMMIT` returns `SQLITE_BUSY`, the transaction stays open, and the `COMMIT` can be retried. In WAL mode readers never hold up a commit.

  • A plain BEGIN in SQLite takes the write lock straight away.
  • BEGIN IMMEDIATE stops other connections from reading the database.
  • BEGIN EXCLUSIVE in WAL mode blocks every reader until COMMIT.
  • BEGIN DEFERRED means SQLite defers constraint checks until COMMIT.
  • BEGIN can be nested in SQLite like a savepoint.