Browse topics

Row locking

Version
19
Review
Draft

Summary#

A locking clause on SELECT takes row locks held until the transaction ends or rolls back to a savepoint taken before the locks. SKIP LOCKED lets queue workers pass over rows that another transaction holds. NOWAIT reports a conflict if a row lock is unavailable.

Syntax#

sql
SELECT column_list
FROM table_name AS t
WHERE condition
ORDER BY key_column
LIMIT row_count
FOR UPDATE [OF t] SKIP LOCKED;

SELECT column_list FROM table_name
WHERE condition
FOR NO KEY UPDATE NOWAIT;

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind. The temporary table is visible to one session only, so nothing competes for its rows. On a shared queue table, a second worker skips rows whose locks conflict, and NOWAIT raises an error if a row lock is unavailable.

sql
BEGIN;

CREATE TEMPORARY TABLE jobs (
    job_id  integer PRIMARY KEY,
    state   text NOT NULL,
    payload text NOT NULL
);

INSERT INTO jobs VALUES
    (1, 'done', 'resize'), (2, 'queued', 'email'),
    (3, 'queued', 'export'), (4, 'queued', 'index');

-- Lock up to two queued jobs and claim them in the same statement.
WITH next_jobs AS MATERIALIZED (
    SELECT job_id
    FROM jobs
    WHERE state = 'queued'
    ORDER BY job_id
    LIMIT 2
    FOR UPDATE SKIP LOCKED
),
claimed AS (
    UPDATE jobs AS j
    SET state = 'running'
    FROM next_jobs AS n
    WHERE j.job_id = n.job_id
    RETURNING j.job_id, j.payload
)
SELECT job_id, payload FROM claimed ORDER BY job_id;

-- NOWAIT checks for conflicting row locks.
SELECT job_id, state
FROM jobs
WHERE job_id = 4
FOR NO KEY UPDATE NOWAIT;

SELECT job_id, state FROM jobs ORDER BY job_id;

ROLLBACK;

Expected output#

Text
job_id|payload
2|email
3|export
(2 rows)
job_id|state
4|queued
(1 row)
job_id|state
1|done
2|running
3|running
4|queued
(4 rows)

Common mistakes#

ERROR: could not obtain lock on row in relation is what NOWAIT raises when another transaction holds the row. The error aborts the current transaction, so roll back before retrying.

In autocommit mode, a standalone SELECT ... FOR UPDATE releases its locks when that statement finishes. A later UPDATE is then unprotected. Claim rows in one statement, as above, or keep both steps in one transaction. SKIP LOCKED can omit rows from a report. Both NOWAIT and SKIP LOCKED apply to row locks. The statement can still wait for a table lock.

Version applicability#

FOR NO KEY UPDATE and FOR KEY SHARE arrived in PostgreSQL 9.3, and SKIP LOCKED in 9.5. The example's AS MATERIALIZED keyword requires PostgreSQL 12 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0