FOR NO KEY UPDATE Weakens Row Locks

Compare FOR UPDATE with FOR NO KEY UPDATE and FOR KEY SHARE, then check which row lock modes still block foreign key checks.

SqlData Integrity

Code

snippet
CREATE TABLE accounts (
  id bigint PRIMARY KEY,
  balance numeric(12, 2) NOT NULL
);

INSERT INTO accounts (id, balance) VALUES (1, 100.00), (2, 250.00);

BEGIN;

-- FOR NO KEY UPDATE allows concurrent foreign keys that take KEY SHARE locks.
SELECT id, balance
FROM accounts
WHERE id = 1
FOR NO KEY UPDATE;

UPDATE accounts SET balance = balance - 10 WHERE id = 1;

-- FOR KEY SHARE is the weakest row lock and still conflicts with FOR UPDATE.
SELECT id
FROM accounts
WHERE id = 2
FOR KEY SHARE;

COMMIT;

-- FOR UPDATE takes the strongest row-level lock.
SELECT id, balance
FROM accounts
WHERE id = 1
FOR UPDATE;

SELECT id, balance
FROM accounts
WHERE id = 2
FOR NO KEY UPDATE;

How the snippet works

The file runs SELECT / INSERT / UPDATE / CREATE statements, touching accounts.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the accounts table.

Statements that matter

SELECT id, balance
FROM accounts
WHERE id = 1
FOR NO KEY UPDATE;
SELECT id, balance
FROM accounts
WHERE id = 2
FOR NO KEY UPDATE;
SELECT id, balance
FROM accounts
WHERE id = 1
FOR UPDATE;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`accounts` — referenced directly, no join needed.