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.

SqlData Integrity

Code

snippet
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

FAQ

What are the relations in play here?
The references are `accounts`.