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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables does this file reference?
- `accounts` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.