REPEATABLE READ Snapshot Per Transaction
REPEATABLE READ pins one snapshot for the whole transaction, so re-reads return identical rows even after other sessions commit changes.
Code
-- REPEATABLE READ:事务首条查询建立快照,之后整个事务沿用
CREATE TABLE ticks (id int PRIMARY KEY, price numeric NOT NULL);
INSERT INTO ticks VALUES (1, 100.0);
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT price FROM ticks WHERE id = 1; -- 100.0,快照在此刻建立
-- 另一个会话提交的修改对本事务不可见(快照冻结)
UPDATE ticks SET price = 999.0 WHERE id = 1;
SELECT price FROM ticks WHERE id = 1; -- 仍是 100.0:可重复读
COMMIT;
-- 提交后新事务看到 999.0:快照随事务重建
SELECT price FROM ticks WHERE id = 1;
-- 对比 READ COMMITTED:每条语句都用最新快照,重复读会漂移
SHOW default_transaction_isolation;The story inside the file
SELECT / INSERT / UPDATE / CREATE statements share the script, touching ticks.
Breaking the statements into their working parts: a WHERE clause limiting a statement to the rows that qualify; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Putting it to use
Point it at the ticks table.
Core lines
SELECT price FROM ticks WHERE id = 1; -- 100.0,快照在此刻建立
SELECT price FROM ticks WHERE id = 1; -- 仍是 100.0:可重复读
UPDATE ticks SET price = 999.0 WHERE id = 1;
Interactive Tools for This Topic
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.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.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
- Which relations are involved here?
- `ticks`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.