READ ONLY Transactions Reject Writes

Open read-only transactions that reject writes and row locks, then reset the session default after reporting queries finish.

SqlSecurity Boundaries

Code

snippet
-- 只读事务:READ ONLY transactions reject writes, suitable for reports
BEGIN READ ONLY;

SELECT count(*) AS account_count FROM accounts;
SELECT id, balance FROM accounts ORDER BY id LIMIT 5;

-- 写入会失败:ERROR: cannot execute INSERT in a read-only transaction
-- INSERT INTO accounts (id, balance) VALUES (99, 0);

ROLLBACK;

-- 另一种写法:先 BEGIN,再 SET TRANSACTION READ ONLY
BEGIN;
SET TRANSACTION READ ONLY;
SELECT now() AS snapshot_time;
COMMIT;

-- 会话级默认只读,可用 RESET 恢复
SET default_transaction_read_only = on;
SHOW default_transaction_read_only;
RESET default_transaction_read_only;

-- 只读事务中 SELECT ... FOR UPDATE 也会被拒绝,因为它需要写锁
-- SELECT id FROM accounts FOR UPDATE;

How it works

Several statements share this file — SELECT, with accounts among the objects involved.

Breaking the statements into their working parts: COUNT aggregation; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

Applying it

Point it at the accounts table — the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

SELECT id, balance FROM accounts ORDER BY id LIMIT 5;
SELECT count(*) AS account_count FROM accounts;
SELECT now() AS snapshot_time;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`accounts`.