Databases 5 min read

Understanding SELECT ... FOR UPDATE Locking in MySQL: Row vs. Table Locks

This article explains how MySQL's SELECT ... FOR UPDATE statement adds a pessimistic lock, detailing when it results in row-level locking versus table-level locking based on the presence of indexes or primary keys, and demonstrates the behavior with multiple practical examples.

Top Architect
Top Architect
Top Architect
Understanding SELECT ... FOR UPDATE Locking in MySQL: Row vs. Table Locks

The author, a senior architect, explains that a normal SELECT statement does not acquire locks, but SELECT ... FOR UPDATE adds a pessimistic lock; the lock type depends on whether the query uses an indexed column or primary key.

If an index or primary key is used, the statement acquires a row lock; without an index, it escalates to a table lock.

Before testing, automatic commit must be disabled by executing SET @@autocommit=0; , where 0 indicates manual commit.

Table creation SQL used for the experiments:

//id is primary key
//name is unique index
CREATE TABLE `user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) DEFAULT NULL,
  `age` INT(11) DEFAULT NULL,
  `code` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_age` (`age`) USING BTREE
) ENGINE=INNODB AUTO_INCREMENT=1570068 DEFAULT CHARSET=utf8;

Example 1: A transaction selects a row by primary key id and holds the lock, while a second transaction attempts to update the same row and is blocked, demonstrating a row lock.

Example 2: A second transaction updates a different row (id=2). The lock behavior is observed similarly, confirming row-level locking when the primary key is used.

Example 3 (Indexed field): The age column has a unique index. When queries use this indexed column, the lock remains at the row level.

Example 4 (Non‑indexed field): Using the ordinary column code (no index) for the query causes the SELECT ... FOR UPDATE to lock the entire table, as demonstrated by the blocked updates.

Result: When the query condition uses an indexed column or primary key, SELECT ... FOR UPDATE acquires a row lock; otherwise, it locks the whole table.

SQLDatabaseMySQLRow Locktable lockSELECT FOR UPDATE
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login 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.