Databases 3 min read

Mastering MySQL Pessimistic Locks: How SELECT … FOR UPDATE Works

This article explains the concept of MySQL pessimistic locking, its implementation via row‑level locks in InnoDB, and provides step‑by‑step SQL examples showing how SELECT … FOR UPDATE secures data against concurrent modifications.

Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Mastering MySQL Pessimistic Locks: How SELECT … FOR UPDATE Works

MySQL is frequently asked in large tech companies; this article provides a detailed explanation of MySQL pessimistic locks.

MySQL Pessimistic Lock

Pessimistic locking assumes that conflicts will always occur, so it locks data during processing to prevent other transactions from modifying the same data simultaneously. In other words, lock first, then operate.

Implementation principle of MySQL pessimistic lock

In MySQL (InnoDB engine), pessimistic locks are mainly implemented through row‑level locks.

最新文章
最新文章

Before modifying or querying data, the current transaction places an exclusive lock on the relevant rows.

A typical SQL statement is SELECT ... FOR UPDATE, which locks the selected rows.

<ol><li>-- 开启事务</li><li>BEGIN;</li><li>-- 悲观锁:锁定账户为 id = 123 的行,防止其他事务修改</li><li>SELECT balance FROM accounts WHERE id = 123 FOR UPDATE;</li><li>-- 假设查到的余额为 1000</li><li>-- 业务逻辑:进行扣款,扣除 500</li><li>UPDATE accounts SET balance = balance - 500 WHERE id = 123;</li><li>-- 提交事务</li><li>COMMIT;</li></ol>

In this example, the SELECT ... FOR UPDATE statement immediately places an exclusive lock on the row where id = 123.

If another transaction attempts a FOR UPDATE on the same row, it will wait until the first transaction commits or rolls back, releasing the lock.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

transactionInnoDBmysqlrow-level lockSELECT FOR UPDATE
Mike Chen's Internet Architecture
Written by

Mike Chen's Internet Architecture

Over ten years of BAT architecture experience, shared generously!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.