Predict the output
What does the SELECT print after one UPDATE in PostgreSQL?
CREATE TABLE t (id int PRIMARY KEY, v int);
INSERT INTO t VALUES (1, 10);
SELECT xmin = xmin FROM t; -- warm-up
UPDATE t SET v = 11 WHERE id = 1;
SELECT count(*) AS live, v FROM t GROUP BY v;Hint 1 of 1
Which versions does your snapshot see?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A t then 1|11
Correct. The warm-up prints t; the old version still exists on disk as a dead tuple, but no snapshot sees it, so one live row with v = 11.
An UPDATE in PostgreSQL writes a new row version and marks the old one dead. Queries only see versions visible to their snapshot, so there is one live row with v = 11 until VACUUM reclaims the dead one.
Why not the others?
- B
tthen2|11. Dead versions are invisible to queries; count(*) counts visible rows only. - C
tthen1|10. The update committed (autocommit), so the new version is visible. - D An error: xmin can't be compared. System columns can be selected and compared like ordinary columns.
| live | v |
|---|---|
| 1 | 11 |
(1 row)