Skip to content

Indexes, query plans and transactions

Phase 3 · Data and state · 14 min read

What you'll be able to do

  • Choose an index for a query and check whether the database uses it.
  • Make a multi-row change atomic and explain what each ACID property protects.
  • Recognize a concurrent update bug and choose a safe update or retry strategy.

Why a query scans rows

Suppose an events table has one million rows and you ask for one user's recent events. Without a useful index, the database may inspect all one million rows: a full scan, with work proportional to n. An index is an extra, sorted structure containing keys and pointers to rows. A B-tree keeps those keys in ordered pages, so finding a starting point takes roughly O(log n) page steps; returning k matching rows still takes additional work proportional to k.

A B-tree lookup walks one path from the root to the key: about log n page steps.

At one million keys, log2(1,000,000) is about 20 comparisons in an ideal binary tree. Real B-trees hold many keys per page, so the exact page count differs. The useful comparison is bounded navigation plus matches versus examining every row. An index costs disk space and makes inserts, deletes, and updates to indexed columns do extra work.

Choose an index for the query

Start with columns used in WHERE and JOIN, then consider whether the index can also supply ORDER BY order. Selectivity means how much a condition narrows the result. An index on a nearly unique user_id often helps; an index on a flag that is true for half the table may save little. The optimizer can still choose a scan when many rows match, even if an index exists.

For this query, (user_id, created_at) is a useful composite index:

CREATE INDEX events_user_time ON events(user_id, created_at);
SELECT payload FROM events
WHERE user_id = 42 AND created_at >= '2026-11-01'
ORDER BY created_at;

The leftmost-prefix rule means the index can efficiently find a user_id alone, or a user_id followed by a time range. A time-only condition generally cannot use this index to jump straight to a time range because times from different users are interleaved. Some engines have exceptions or alternative scan strategies; inspect the plan. If the index also contains every column the query needs, a covering index can avoid fetching the table row. Adding payload just for that benefit may make the index much larger.

Ordinary indexes usually cannot efficiently seek through WHERE DATE(created_at) = ... or LIKE '%report': the first transforms the stored key, and the second has no fixed prefix. Rewrite a date filter as a range on created_at; a specialized expression or text-search index is another option when supported. A low-cardinality flag alone is often weak. Every extra index adds maintenance to inserts and deletes, and to updates of its indexed columns, so index measured queries rather than every column.

Ask the database what it will do

Use EXPLAIN QUERY PLAN in SQLite or EXPLAIN in PostgreSQL before guessing. Look for a table scan versus an index search, the index chosen, and any extra sort. PostgreSQL's EXPLAIN ANALYZE executes the query and adds observed timing and row counts; use care with statements that write data. Plan wording and choices vary by database and data distribution.

EXPLAIN QUERY PLAN
SELECT payload FROM events
WHERE user_id = 42 AND created_at >= '2026-11-01'
ORDER BY created_at;

One query can also become slow because application code issues it repeatedly. If code fetches 100 jobs, then fetches each job's owner separately, that is N+1 queries: 1 + 100 = 101 queries. If they run one after another against a remote database and each costs an illustrative 5 ms of round-trip latency, latency alone totals 505 ms. A join or batched IN query can fetch the same data in far fewer trips. Inspect query logs as well as individual plans.

A transfer of 30 from account A to B must not stop after debiting A. A transaction groups the two changes:

BEGIN;
UPDATE accounts SET balance = balance - 30
  WHERE id = 'A' AND balance >= 30;
UPDATE accounts SET balance = balance + 30 WHERE id = 'B';
COMMIT;
-- On an error or failed check: ROLLBACK instead.

This is a sketch until the application adds its checks. Before COMMIT, it must verify that each UPDATE affected exactly one row; otherwise it must ROLLBACK. A zero-row update is not an SQL error, so a missing account B would let the debit commit alone.

Atomicity means either both writes commit or neither does. Consistency means committed data obeys the constraints and invariants you actually enforce; a CHECK (balance >= 0) and validation of account IDs do not appear by magic. Isolation controls what concurrent transactions can observe or change. Durability means committed changes survive a crash under the database's durability settings; a write-ahead log is a common way to record changes before applying them to data pages.

The balance >= 30 condition makes the funds check part of the debit. Some database drivers begin transactions implicitly for writes, while others autocommit each statement. Know which mode your connection uses: two individually committed statements are not one transfer.

In Python's sqlite3 with its default transaction control, with conn: commits or rolls back on exit but does not itself begin a transaction. In autocommit mode (isolation_level=None), each statement inside it still commits alone. If the caller already has a transaction open, a failure rolls back the caller's earlier work too. A savepoint solves both: SAVEPOINT move starts a transaction if none is open. On success, run RELEASE move, which commits if the savepoint opened the transaction; on failure, run ROLLBACK TO move and then RELEASE move. Inside a caller's transaction, this undoes only your statements and leaves the final commit to the caller.

What concurrency can change

Think of A and B as separate transactions. These timelines describe possible anomalies, not promises that every database permits them:

Anomaly Small timeline Problem
Dirty read A writes 9; B reads 9; A rolls back B saw data that never committed
Non-repeatable read A reads row = 5; B commits row = 6; A rereads Same row changed within A
Phantom A counts 4 matching rows; B inserts a match and commits; A recounts 5 Result set changed
Lost update A reads 5; B reads 5; A writes 6; B writes 6 Two increments produced only one
Write skew A and B each see two workers on call; each removes a different worker Both writes succeed; no worker remains

Read committed prevents dirty reads but may allow later reads to see new commits. Repeatable read or snapshot isolation generally keeps earlier reads stable; exactly how phantoms and write conflicts behave differs by database. Snapshot isolation can still allow write skew because the two transactions change different rows. Serializable aims for an outcome equivalent to some one-at-a-time order, often by aborting a conflicting transaction. Its caller must be ready to retry the whole transaction. Check your database's isolation documentation for precise guarantees.

Defend the invariant

For a counter, UPDATE usage SET tokens = tokens + 1 WHERE id = 7 computes the increment in the database, avoiding an application read-modify-write race. For a transfer or job claim involving several checks, use a short transaction. PostgreSQL's SELECT ... FOR UPDATE can lock selected rows while you decide; SQLite has different locking behavior and does not use that syntax. An optimistic alternative is a version column: UPDATE ... SET value = ?, version = version + 1 WHERE id = ? AND version = ?. If zero rows change, someone else won; reload and retry if the operation is safe to repeat. A unique constraint is the final guard against duplicate claims or identifiers, even when application code checks first.

Connection pooling reuses a limited number of open database connections so each request does not pay connection setup cost. Each transaction occupies a connection. Long transactions hold locks or old row versions, can block other work, and can cause storage bloat in databases that retain old versions. Never keep one open during a network request or model call; commit promptly, and retry deadlocks or serialization failures with a bounded policy.

For AI engineers

For AI engineers

Two queue workers can both read the same unclaimed job and run it twice. Claim it with one conditional update or a transaction and a uniqueness rule. Concurrent token-usage updates need an atomic increment, too. Feature-store point lookups need indexes on their lookup keys. A slow analytical scan on the production database competes with user-facing inference requests; move heavy analysis to a read replica or warehouse when the workload warrants it. Your training script's database reads become an engineering problem once other people depend on that database.

Common mistakes

  • Indexing every column and forgetting the disk and write cost.
  • Assuming an index will be used without checking a plan on representative data.
  • Using a huge OFFSET: the database still has to walk past skipped rows; use a stable cursor or keyset when possible.
  • Reading a value in Python, adding one, then writing it without an atomic update, lock, or version check.
  • Holding a transaction open while waiting for a model or API call.
  • Treating deadlocks or serialization failures as permanent errors instead of retryable transaction failures.

Check yourself

You have an index on (tenant_id, created_at). Which filter is more likely to use it for a targeted search: tenant_id = 7, or created_at >= yesterday alone?

tenant_id = 7 starts with the index's leftmost column. The time-only filter generally cannot jump directly to the desired range in that index; check the actual plan.

Two workers each read a usage count of 10, add one in Python, and write 11. What failed, and what single SQL change fixes this case?

This is a lost update: two increments yielded one. UPDATE usage SET count = count + 1 WHERE id = ? lets the database perform each increment atomically.

A transfer debits A and commits, then its credit to B fails. Which ACID property was lost, and what should the transaction boundary include?

Atomicity was lost. Put both updates and their checks inside one transaction, committing only after both succeed and rolling back on failure.

Under snapshot isolation, two doctors each see another doctor on call and each removes their own on-call row. Why might both commits succeed, and what stronger guarantee addresses it?

They changed different rows, so a row-level write conflict may not occur: this is write skew. Serializable isolation can reject one transaction; enforce the invariant and retry the rejected transaction.

Lab

In code/indexes-transactions/, add an index and repair a query so SQLite plans an index search. Implement a transfer that applies both account changes or neither, whatever the transaction mode. Interleave two generators on one connection to simulate stale reads, then implement an atomic increment. Finish with a version-checked update that reports conflicts. Run: cd code/indexes-transactions && PYTHONPATH=starter python -m pytest tests -q The starter should fail; use the README and tests to complete all five tasks.

Go deeper