Row-level locking

Also known as: row lock

On this page 7

Row-level locking is a concurrency control technique in which a database transaction acquires locks on individual rows rather than on whole pages or tables. In databases and in the theory of transactions, it is the finest common lock granularity, allowing many transactions to modify different rows of the same table at the same time while still protecting each row from conflicting concurrent changes.

A row lock is held until the transaction commits or rolls back, which is how engines enforce the isolation guarantee of ACID. Row-level locking is the default write-locking behavior of most modern relational engines, including PostgreSQL, Oracle Database, MySQL with InnoDB and SQL Server, although each implements it differently and combines it with MVCC for reads.

How row-level locking works

When a transaction updates or deletes a row, the engine places an exclusive lock on that row before changing it. Any other transaction that tries to write the same row must wait until the lock is released at commit or rollback, or fail immediately if it requested a no-wait mode. Transactions working on other rows proceed without interference.

Engines record row locks in different places. Some keep entries in a central lock manager in memory, while others store lock information in the row header itself, which avoids memory limits on the number of locks. The storage choice affects whether the engine ever needs lock escalation, the conversion of many fine locks into one coarse lock.

The table below lists the common row lock modes and how they interact.

Lock modeTypical triggerBlocksAllows
Shared lockSELECT ... FOR SHAREWriters to the rowOther shared readers
Exclusive lockUPDATE, DELETE, SELECT ... FOR UPDATEOther writers and lockersPlain MVCC reads
Update lockRead with intent to modifyOther update locksShared readers
Intention lockPlaced on the table above row locksConflicting table locksOther row-level work
Common row lock modes

Intention locks deserve a brief note. They signal at table level that rows inside are locked, so a request for a full table lock can detect a conflict without inspecting every row.

Lock granularity compared

Lock granularity is a trade-off between concurrency and overhead. Finer locks let more transactions run in parallel but require more bookkeeping, while coarser locks are cheap to manage yet serialize work that would not actually conflict.

The comparison below places row-level locking among the other granularities.

GranularityConcurrencyManagement overheadTypical use
Row-level lockingHighestHighest per lockOLTP workloads with many small writes
Page-level lockingModerateModerateOlder engines and some index structures
Table-level lockingLowestLowestBulk loads, schema changes, simple engines
Database-level lockingMinimalMinimalEmbedded or single-writer systems
Lock granularity levels

Row locks protect existing rows only. They do not by themselves stop another transaction from inserting a new row that matches a query, which is the source of a phantom read. Engines that prevent phantoms under stricter isolation levels add gap locks, next-key locks or predicate locks that cover ranges of index keys rather than single rows.

Row locks, MVCC and isolation levels

In engines that use MVCC, ordinary reads do not take row locks at all. A reader sees a consistent snapshot built from older row versions, so writers and readers do not block each other. Row locks therefore mainly coordinate writers with writers and with explicit locking reads.

This combination changes what isolation levels mean in practice. At Read Committed, a writer that waits for a row lock usually re-reads the latest committed version once the lock is released. At Repeatable Read or Serializable, some engines instead raise a serialization failure that the application must retry.

The table below summarizes how row locking contributes at each standard isolation level.

Isolation levelRow lock roleAdditional mechanism
Read UncommittedWrite locks onlyDirty reads remain possible
Read CommittedWrite locks held to commitSnapshot per statement
Repeatable ReadWrite locks held to commitSnapshot per transaction or range locks
SerializableWrite and often read locksPredicate locks or conflict detection
Role of row locks at each isolation level

Explicit row locking in application code

Applications use explicit row locks to implement pessimistic locking, in which a transaction claims a row before deciding how to change it. The typical pattern reads a row with SELECT ... FOR UPDATE, checks a business rule, then writes, so no concurrent transaction can change the row in between.

Modern engines add options that make this pattern scale. NOWAIT returns an error at once if the row is locked, and `SKIP LOCKED` ignores rows already locked by others, which turns an ordinary table into an efficient job queue where many workers claim different tasks without collisions. Optimistic locking, by contrast, takes no lock and instead checks a version column at write time.

  • Use `FOR UPDATE` when a read-check-write sequence must be atomic and conflicts are frequent.
  • Use `SKIP LOCKED` for queue consumers that should never wait on one another.
  • Use optimistic locking when conflicts are rare and transactions span user think time.

Deadlocks, contention and other pitfalls

Row-level locking reduces contention but does not remove it, and several failure modes appear under load. The most visible is the deadlock, in which two transactions each hold a row the other needs. Engines detect the cycle and roll back one victim transaction, so applications must be prepared to retry.

The following table connects common symptoms with their causes and fixes.

SymptomLikely causeRemedy
Frequent deadlock errorsRows locked in inconsistent orderLock rows in a fixed order, such as by key
Long lock waits on one rowHot row such as a shared counterShard the counter or batch updates
Sudden table-wide blockingLock escalation after many row locksCommit in smaller batches
Updates lock far more rows than expectedMissing index on the filter columnIndex the predicate so fewer rows are scanned
Idle sessions blocking othersTransactions left open by the applicationSet lock and idle timeouts
Row locking problems and remedies

The missing-index case is easy to overlook. Without a usable index, an UPDATE may need to examine and sometimes lock many rows to find the targets, especially in engines that lock index ranges, so good indexing is part of lock hygiene. Keeping transactions short and focused remains the most effective general remedy.

In everyday language

Row-level locking is like a shared spreadsheet where you can only lock the single line you are editing. Everyone else keeps working on other lines at the same time. If two people want the very same line, the second person waits until the first is finished.

Locking a whole table would be like locking the entire spreadsheet for one small change. Locking only one row keeps everyone moving and still prevents two people from overwriting each other’s work.

Seen in the real world

A ticketing platform sells seats for a concert hall with 2,000 numbered seats, each stored as a row. When sales open, hundreds of buyers try to reserve seats within the first minute. Each checkout transaction runs SELECT ... FOR UPDATE on the chosen seat, confirms it is still free, marks it as held and commits within a few milliseconds.

Because only the chosen rows are locked, buyers picking different seats never wait for one another, and two buyers who click the same seat cannot both succeed: the second one waits briefly, sees the seat already held and is offered another. A background worker that releases expired holds uses `SKIP LOCKED` so it never stalls behind an active checkout. The result is no double bookings and steady response times even at peak demand.