Skip to content
JZLeetCode
Go back

System Design - How TiDB Executes UPDATE in Source Code

Table of contents

Open Table of contents

One SQL statement has a read side and a write side

Consider an online shop that raises the price of one product:

UPDATE products
SET price = price * 1.05
WHERE id = 7;

The SQL layer first needs to find the matching row. It then evaluates the assignment using the old row, checks whether the new values are valid, and writes the row and any affected indexes. TiDB keeps these steps inside the statement’s transaction so another query does not observe a new row value with an old index entry.

This walkthrough follows a single-table UPDATE through the current TiDB source. It focuses on the executor, the shared row-update helper, and the table implementation. Planning details and multi-table assignment merging are outside the main path here.

The route through the components

The planner represents an update with both a selection plan and an ordered list of assignments. The executor builder turns that plan into an UpdateExec whose child produces the rows to update. The table layer converts the row change into key-value mutations held by the transaction.

SQL: UPDATE products ...
             |
             v
      PhysicalUpdate
      SelectPlan + assignments
             |
             v
 executorBuilder.buildUpdate
             |
             v
 UpdateExec -- reads matching rows and handles
             |
             v
 updateRecord -- checks values and constraints
             |
             v
 TableCommon.UpdateRecord
   |                       |
   | update index keys     | encode row key
   +-----------+-----------+
               |
               v
       transaction MemBuffer
               |
         commit protocol
               v
             TiKV

This source path is divided among three main pieces: executorBuilder.buildUpdate, UpdateExec, and the shared updateRecord helper plus TableCommon.

1. The plan finds rows and carries their handles

executorBuilder.buildUpdate builds v.SelectPlan as the update executor’s child. That child is responsible for the normal query work behind the WHERE clause: using its scan and filter plan to produce matching rows. The builder also passes the update assignments, target table metadata, column positions, and handle information into UpdateExec.

The handle is important. It identifies the physical row that TiDB will change, even if the query found that row through a secondary index. The child therefore supplies both the values needed to evaluate the assignment and enough information to identify the target record.

For our example, the child might produce the row (id=7, price=20.00) along with the handle for row 7. UpdateExec can then compute the new price, 21.00, while keeping the same row identity.

2. UpdateExec builds each new row

UpdateExec.Next drains its child once by calling updateRows. The method opens or retrieves the statement transaction, then asks the child for chunks of matching rows. For each row, prepare builds its handle, and composeNewRow evaluates assignments that depend on row values. TiDB uses a faster path when every assignment is constant.

The executor passes the old row, the composed new row, the handle, and the assignment flags to its exec method. That method tracks matched rows and calls updateRecord. A row that appears more than once through a join or update shape is tracked so TiDB does not apply the update twice. For a simple single-table query, the common case is one child row per matched record.

At this stage, the new values are still part of TiDB’s execution state. UpdateExec has not sent an SQL UPDATE command to TiKV. The next helper turns the proposed row into checked, indexed key mutations.

3. updateRecord decides what really changed

The shared updateRecord function lives in pkg/executor/write.go; INSERT with ON DUPLICATE KEY UPDATE uses it too. It compares the old and new columns and records which values actually changed. If the new row is identical to the old row, it counts the row as touched and returns without writing a new row value.

That distinction explains why SQL clients can report different counts for matched rows and changed rows. An UPDATE can match a record while leaving its stored values untouched.

When values do change, the helper applies automatic ON UPDATE timestamp behavior, evaluates generated columns, and checks constraints and nullability. It also determines whether a primary or common-handle column changed. That decision selects one of two write paths:

The helper also runs foreign-key checks and cascades when those features apply. A normal update is therefore more than a direct assignment into a row buffer; it is the point where SQL-level value rules meet table-level mutations.

4. The table layer keeps row and index keys together

For the unchanged-handle path, TableCommon.UpdateRecord starts a staging area in the transaction’s MemBuffer. It checks row constraints, rebuilds affected indexes, encodes the new row, and writes it into that same buffer. If the work succeeds, it releases the staging area; on error, cleanup discards the staged part.

The touched flags passed from updateRecord help the table layer avoid rebuilding indexes that cannot be affected by the changed columns. In rebuildUpdateRecordIndices, TiDB checks whether each writable index depends on a changed column. If it does, TiDB removes the old index key and builds the key from the new row. Indexes that do not depend on changed values can often keep their existing entries.

For the example table, updating price requires a new record value. If there is an index on price, its old key must also be removed and a new key added. If the only secondary index is UNIQUE(sku), and sku is unchanged, that index does not need a new logical key for this update.

The row record and the index changes are staged in the same transaction. This is the important invariant: transaction commit makes the set of key mutations visible together, and a failed statement or transaction does not commit just the row or just the index.

What happens if the handle changes?

Some updates modify a clustered primary key or another column that forms the row handle. In that case, TiDB cannot overwrite the same record key because the key itself is derived from the handle. updateRecord uses RemoveRecord for the old row and AddRecord for the replacement. Both operations use the same transaction and staging mechanism, and the add path builds the indexes for the replacement row.

This is why updating a handle column can cost more than changing a non-indexed value. It changes the row’s identity in storage, not only one value inside the row.

The boundary between TiDB and TiKV

The table layer writes mutations into TiDB’s transactional MemBuffer. At commit, TiDB’s transaction client sends the KV changes through the transaction protocol to TiKV. In the ordinary two-phase-commit path, TiKV’s Prewrite command checks and prepares the mutations, and Commit finalizes them. TiKV also supports optimized commit modes such as async commit and one-phase commit, so a particular transaction may not always use the same sequence.

The important boundary is that UpdateExec decides what should change, while the transaction layer and TiKV decide when the KV mutations become committed and visible. A row update is not durable simply because TableCommon.UpdateRecord returned successfully; the surrounding transaction still has to commit.

Settings worth recognizing

SettingWhat it affects
tidb_dml_max_execution_timeA DML-specific execution-time limit. TiDB’s statement adapter recognizes UPDATE as transactional DML and applies this setting when configured.
tidb_enable_batch_dml, tidb_batch_insert, tidb_batch_delete, tidb_dml_batch_sizeThe legacy batch-DML path concerns INSERT and DELETE, not this UpdateExec row loop. The docs mark batch DML deprecated because splitting work across transactions changes atomicity.

The second row is an easy naming trap: a batch-size setting does not mean that a large UPDATE is automatically split into independent commits. TiDB’s code checks the batch-insert and batch-delete modes separately. For UPDATE, reason about the surrounding transaction and its timeout instead.

References

  1. TiDB documentation, UPDATE and Transaction Overview.
  2. TiDB documentation, System Variables — includes the deprecated batch-DML settings and their transaction-boundary caveats.
  3. PingCAP, How Distributed ACID Transactions Work in TiDB — background on TiDB’s distributed transaction path.
  4. TiDB source, buildUpdate, UpdateExec, and updateRows.
  5. TiDB source, updateRecord, TableCommon.UpdateRecord, and index rebuilding.
  6. TiDB source, tidb_dml_max_execution_time and DML timeout selection.
  7. TiKV source, Prewrite and commit.
Share this post on:

Previous Post
System Design - How the Model Context Protocol Connects AI Apps to Tools
Next Post
LeetCode 328 Odd Even Linked List