SELECT FOR SHARE Read Locking
FOR SHARE takes a row lock that blocks writers but permits other readers, unlike the plain snapshot read that lets a concurrent UPDATE slip between checks.
Code
BEGIN;
-- 普通 SELECT 走 MVCC 快照:不加锁,
-- 别的事务可以在你读取之后随时 UPDATE 这一行
SELECT account_id, balance_cents
FROM accounts
WHERE account_id = 42;
-- FOR SHARE:获取共享锁——其他事务仍可读(也拿共享锁),
-- 但 UPDATE / DELETE 会阻塞到本事务结束
SELECT balance_cents
FROM accounts
WHERE account_id = 42
FOR SHARE;
-- FOR NO KEY UPDATE / FOR UPDATE:排他行锁,连其他共享锁也要排队
SELECT balance_cents
FROM accounts
WHERE account_id = 42
FOR UPDATE;
COMMIT;
-- 两阶段校验场景(读余额 → 基于余额做决定 → 写回)必须用 FOR SHARE 以上,
-- 否则决定依据的快照在写入前可能已经过期What the code does
What runs here is SELECT / UPDATE — accounts are the objects involved.
Breaking the statements into their working parts: a WHERE clause that keeps only the rows a statement is meant to touch.
Applying it
Point it at the accounts table.
Statements that matter
SELECT balance_cents
FROM accounts
WHERE account_id = 42
FOR UPDATE;
SELECT account_id, balance_cents
FROM accounts
WHERE account_id = 42;
SELECT balance_cents
FROM accounts
WHERE account_id = 42
FOR SHARE;
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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- The references are `accounts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.