READ ONLY Transactions Reject Writes
Open read-only transactions that reject writes and row locks, then reset the session default after reporting queries finish.
Code
-- 只读事务: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
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.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- Name the tables involved in this file.
- `accounts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.