Skip to content
IT glossary
DatabasesUpdated December 3, 2026

Database locks

Блокировки в базе данных

Database locks coordinate operations that touch the same data. When two operations conflict, the database can make one wait until the other releases its lock.

Also known as: SELECT FOR UPDATE, row lock

What a lock protects

Suppose a worker reads a job marked ready and is about to claim it. If another worker reads the same status before the first worker updates it, both may think they own the job. A row lock lets one transaction read the job and make its decision before another transaction can change the row or acquire a conflicting lock on it.

Locks have a scope and a mode. A row lock targets a particular row; a table lock applies to the table and, depending on its mode, can block a broader range of operations. Two locks can coexist on the same resource if their modes are compatible. For example, a schema change may need a table lock that conflicts even with a plain query, whereas a PostgreSQL row lock taken by FOR UPDATE doesn't block a plain SELECT. With multiversion concurrency control (MVCC), that reader sees the row version visible to its snapshot.

Example: claim a job in PostgreSQL

BEGIN;
SELECT status FROM jobs WHERE id = 42 FOR UPDATE;
-- If a row was returned and its status is 'ready', run:
UPDATE jobs SET status = 'running' WHERE id = 42;
COMMIT;

The SQL comment marks an application-side branch: if the row is missing or no longer ready, the application skips the update and ends the transaction. At PostgreSQL's READ COMMITTED isolation level, a second worker running the same locking query waits and, if the first worker commits the change, reads running. The worker should commit the claim before doing the job so it doesn't hold the lock throughout processing. A plain SELECT is not a substitute: even if it reads ready, it hasn't reserved the row.

When to use an explicit lock

UPDATE and DELETE already lock the rows they modify. For a simple status change, a single UPDATE with WHERE id = 42 AND status = 'ready' can be enough: only the worker that updates a row has claimed the job. Reach for SELECT ... FOR UPDATE when you need to inspect the current data and make a decision across several statements. Keep those statements in one short transaction. In autocommit mode, a standalone locking query releases its lock when that statement's transaction ends, so it can't protect a later statement.

What interviewers ask

Expect to trace two transactions on a timeline. A lock wait is not necessarily a deadlock: if one transaction is waiting and the other can finish, the wait can clear. A deadlock is a cycle: transaction A holds one row and wants another, while transaction B holds the second row and wants the first. PostgreSQL breaks the cycle by aborting one transaction. Locking rows in a consistent order reduces the risk; if retrying is safe, retry the whole aborted transaction so its decisions are based on fresh reads.