Sub topic 2
Looking at Real Pages with pageinspect
This chapter assumes you know basic SQL (CREATE TABLE, INSERT, UPDATE, SELECT), can use psql, and understand what a transaction is. Creating the pageinspect extension requires sufficient privileges.
A page is a fixed 8 KB block inside a table's data file. The pageinspect extension reads those raw bytes from SQL. Start with a small table:
CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance numeric);
INSERT INTO accounts VALUES (1, 'alice', 100), (2, 'bob', 200);
SELECT lower, upper, pagesize
FROM page_header(get_raw_page('accounts', 0));
SELECT lp, lp_off, lp_len, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));page_header shows where free space starts (lower) and ends (upper). heap_page_items lists one line per line pointer, which is the entry that points to each row version on the page.
The tuple header: what every row carries
Each row version, called a tuple, begins with a header. The fixed part is 23 bytes. The t_hoff field gives the full header size, which is padded to a multiple of 8 bytes, so it is usually 24 when the row has no NULLs.
t_xminis the transaction that inserted this row version.t_xmaxis the transaction that deleted or locked it. Zero means no deleter.t_ctidis the address of this row version, or of its newer replacement.
NULLs, alignment, and padding: why column order matters
A NULL takes no data bytes, but when any column is NULL, the header gains a null bitmap. Alignment matters more. A boolean takes 1 byte, but a bigint must start on an 8-byte boundary, so the database inserts padding bytes before it. Compare two tables with the same data:
CREATE TABLE padded (a boolean, b bigint, c boolean, d bigint);
CREATE TABLE compact (b bigint, d bigint, a boolean, c boolean);
INSERT INTO padded SELECT true, g, true, g FROM generate_series(1, 100000) g;
INSERT INTO compact SELECT g, g, true, true FROM generate_series(1, 100000) g;
SELECT pg_relation_size('padded') AS padded_bytes,
pg_relation_size('compact') AS compact_bytes;The padded table usually takes more bytes because of the padding.
Updates and deletes create row versions
PostgreSQL never overwrites a row in place. An UPDATE writes a new tuple and sets the old tuple's t_xmax to the updating transaction. A DELETE only sets t_xmax. The old version stays on the page until VACUUM removes it.
UPDATE accounts SET balance = balance + 50 WHERE id = 1;
SELECT lp, lp_flags, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));The old version's t_ctid points to the new version's line pointer.
Exercise:
Exercise
After the UPDATE above, how many rows does heappageitems return for page 0, and why?
Show answer
Three. The original alice tuple remains with a nonzero txmax and a tctid pointing to the new version. The new alice tuple and bob's tuple are the other two. The old version stays until VACUUM removes it.