Database Locks: When to Use Them Safely
A lock coordinates access when transactions or administrative tasks touch the same data. Databases automatically take the locks needed for commands such as `UPDATE` and `DELETE`; an application can also request a row lock when it must keep another request from changing a value between checking it and acting on it. Locks reduce some concurrency problems but can create waits and deadlocks, so protect only the needed scope and keep the transaction short.
Do locks block reads?
Not every lock blocks every kind of access. With PostgreSQL’s usual MVCC behavior, an ordinary SELECT takes a read-oriented table lock, while data-changing commands take the table and row locks they need. A typical row-level lock makes other transactions that try to change or lock the same row wait, but it does not block ordinary reads. A strong table lock such as ACCESS EXCLUSIVE can block ordinary reads too.
| Goal | PostgreSQL construct | Main effect |
|---|---|---|
| Keep another request from changing selected rows while you inspect and update them | SELECT ... FOR UPDATE | Conflicting updates, deletes, or row-lock requests wait until the transaction ends |
| Claim available work without waiting on already-locked rows | FOR UPDATE SKIP LOCKED | Skips locked rows; useful for queues, but does not provide a consistent full-list view |
| Fail immediately instead of waiting for a conflicting lock | FOR UPDATE NOWAIT | Raises an error when the lock cannot be acquired at once |
| Coordinate access to a table | LOCK TABLE ... IN ... MODE | Makes incompatible table operations wait; can block a broad scope |
In PostgreSQL, some table-level lock names historically contain “row.” For example, ROW EXCLUSIVE is the table lock automatically taken by UPDATE; its name does not mean it locks only one row. Actual row-level locks coordinate conflicting changes to individual rows.
How can you read a value and then update it safely?
Suppose an order worker should process an order only while its status is pending. To prevent another request from processing that same order first, put the lock and check inside one transaction:
BEGIN;
SELECT status
FROM orders
WHERE order_id = 42
FOR UPDATE;
-- The application checks that the locked row is still pending.
UPDATE orders
SET status = 'processing'
WHERE order_id = 42 AND status = 'pending';
COMMIT;This is an illustrative pattern and was not executed. The application must check that the expected row was selected and that the update affected the expected number of rows. If the order is missing or already being processed, it should avoid starting duplicate work. A FOR UPDATE lock lasts until the transaction ends, so do not hold it while waiting for an external API or user input. Complete the necessary database work and commit promptly.
For a simple transition that can be expressed in one condition, a conditional UPDATE may be preferable to an explicit lock. Run UPDATE ... WHERE status = 'pending' and check whether one row changed; this attempts the state transition atomically. The right approach depends on the business invariant and whether other tables must change as part of the same transaction.
When is SKIP LOCKED appropriate?
SKIP LOCKED can help multiple workers claim separate jobs from a queue: a worker skips rows another worker has locked instead of waiting for them. This reduces the chance that two workers select the same job at the same time. But the resulting view omits locked rows and is not a consistent listing of the whole table. Do not use it for a report or screen that must show every matching item.
An illustrative pattern is:
BEGIN;
SELECT job_id
FROM jobs
WHERE status = 'ready'
ORDER BY created_at, job_id
FOR UPDATE SKIP LOCKED
LIMIT 1;
-- Claim the selected job in the same transaction, then commit.
COMMIT;A real queue also needs rules for changing job state, worker crashes, retries, failed processing, and duplicate execution. SKIP LOCKED alone does not guarantee that a job can never be starved or that it runs exactly once. One design is to claim a job and commit quickly, then perform longer external work outside the database transaction.
How can you reduce lock waits and deadlocks?
Locks can make other transactions wait, and long-running transactions retain locks longer. A deadlock is a cycle in which two or more transactions each hold a lock the other needs, so none can proceed. PostgreSQL detects deadlocks and aborts one transaction; applications need to handle the failure and retry safely when appropriate.
Use a consistent lock order across code paths, especially when updating multiple rows; finish transactions before waiting for user or network input; and keep the protected work small. NOWAIT can fail quickly instead of waiting, and timeouts can bound waits. Handle timeout and deadlock errors according to their different causes.
To investigate contention, inspect PostgreSQL’s pg_locks view for outstanding and ungranted locks and the sessions involved. The view helps observe a problem; it does not fix it. Find which queries and transactions hold locks for a long time, then review transaction scope and query plans. Validate a change in a reproducible test environment before applying it to production data.
A safe selection sequence
State the invariant to protect and identify the rows or tables that can conflict.
First check whether a unique/check constraint or a single conditional `UPDATE` is sufficient.
Use a row lock only for read-then-update work that needs one; reserve table locks for operations such as migrations that require broader coordination.
Keep transactions short and acquire multiple row locks in a consistent order.
In a test environment, check expected waits, timeouts, deadlocks, and retry behavior. The SQL examples here were not run, and no database performance or lock timing was measured.
Scope and sources
[PostgreSQL 18: Explicit Locking](https://www.postgresql.org/docs/18/explicit-locking.html)
[PostgreSQL 18: `SELECT` and locking clauses](https://www.postgresql.org/docs/18/sql-select.html)
[PostgreSQL 18: Viewing Locks](https://www.postgresql.org/docs/18/monitoring-locks.html)
[PostgreSQL 18: Transaction Isolation and Concurrency](https://www.postgresql.org/docs/18/transaction-iso.html)
The official PostgreSQL 18 documentation was checked on 2026-11-22. Lock features and behavior are scoped to PostgreSQL; other database products may use different lock types and concurrency controls. The order and queue examples are hypothetical, and their SQL was not executed.