man postgres-internals/tuple-layout
lesson 2 of 30 · Storage
Inside a tuple: alignment, nulls and varlena
One of the last lesson’s exercises compared two rows: (int, bigint) is 40
bytes long, and the same two values as (bigint, int) are 36. Nothing about the
values changed, only their order. This lesson reads the part of a tuple that
comes after the 23-byte header, column by column: where each value starts,
why some bytes are padding, what a NULL costs, and how a text value says how
long it is. Then tinypg learns thirteen data types (ten of them in the tables
below) and builds the same rows as the
server, byte for byte.
Every psql and shell output below comes from one run of
tools/record_tuple_layout.py in the tinypg repository (tag lesson-02)
against PostgreSQL 19.0 on 64-bit ARM macOS, pasted as the script recorded
it; the byte-by-byte tables are decoded by hand from those outputs. The
comparison at the end is python3 -m tinypg compare from the same tag, run on
the fixture this run recorded. As in lesson 1, pageinspect reads the pages.
What a type says about its layout
Four columns of pg_type decide how a value of each type is stored:
SELECT typname, typlen, typbyval, typalign, typstorage FROM pg_type
WHERE typname IN ('bool', 'int2', 'int4', 'int8', 'float4', 'float8', 'oid', 'date', 'timestamp', 'uuid', 'text', 'varchar', 'bytea', 'numeric')
ORDER BY typlen DESC, typname;
typname | typlen | typbyval | typalign | typstorage
-----------+--------+----------+----------+------------
uuid | 16 | f | c | p
float8 | 8 | t | d | p
int8 | 8 | t | d | p
timestamp | 8 | t | d | p
date | 4 | t | i | p
float4 | 4 | t | i | p
int4 | 4 | t | i | p
oid | 4 | t | i | p
int2 | 2 | t | s | p
bool | 1 | t | c | p
bytea | -1 | f | i | x
numeric | -1 | f | i | m
text | -1 | f | i | x
varchar | -1 | f | i | x
(14 rows)
typlenis the size in bytes, or −1 for a variable-length type, a varlena, whose value starts with its own length.typbyvalsays whether the value travels inside aDatum(a machine word) or as a pointer to it. It matters in memory, not on disk.typalignis the boundary the value must start on:cany byte,s2,i4,d8.typstorageis what TOAST may do with a large value of the type:pplain (nothing),xextended (compress and move out of line),mmain (compress, move only as a last resort),eexternal (move, never compress). Lesson 3 is about it; it matters here once.
The comment on typalign in pg_type.h says what the alignment is for and
where it is measured from:
/* ----------------
* typalign is the alignment required when storing a value of this
* type. It applies to storage on disk as well as most
* representations of the value inside Postgres. When multiple values
* are stored consecutively, such as in the representation of a
* complete row on disk, padding is inserted before a datum of this
* type so that it begins on the specified boundary. The alignment
* reference is the beginning of the first datum in the sequence.
*
* 'c' = CHAR alignment, ie no alignment needed.
* 's' = SHORT alignment (2 bytes on most machines).
* 'i' = INT alignment (4 bytes on most machines).
* 'd' = DOUBLE alignment (8 bytes on many machines, but by no means all).
src/include/catalog/pg_type.h, lines 153–165
In a tuple “the beginning of the first datum” is t_hoff, which is always a
multiple of 8, so an offset that is aligned within the data is also aligned in
memory, wherever the page sits in shared buffers.
Column order: 40 bytes or 36
CREATE TABLE ib (a int, b bigint) WITH (autovacuum_enabled = off);
CREATE TABLE
CREATE TABLE bi (b bigint, a int) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO ib VALUES (1, 2) RETURNING xmin;
xmin
------
1094
(1 row)
INSERT 0 1
INSERT INTO bi VALUES (2, 1) RETURNING xmin;
xmin
------
1095
(1 row)
INSERT 0 1
SELECT lp_off, lp_len, t_data FROM heap_page_items(get_raw_page('ib', 0));
lp_off | lp_len | t_data
--------+--------+------------------------------------
8152 | 40 | \x01000000000000000200000000000000
(1 row)
SELECT lp_off, lp_len, t_data FROM heap_page_items(get_raw_page('bi', 0));
lp_off | lp_len | t_data
--------+--------+----------------------------
8152 | 36 | \x020000000000000001000000
(1 row)
t_data is the tuple after its header. In ib, the int takes bytes 0–3
(little-endian 01000000). The bigint must start on a multiple of 8, so
bytes 4–7 are padding, zeros, and the bigint fills 8–15. With the header
that is 24 + 16 = 40. In bi the bigint comes first at 0–7, the int
needs only a multiple of 4 and 8 is one, so it fills 8–11: 24 + 12 = 36.
The code that does this is fill_val(), which heap_form_tuple() calls,
through heap_fill_tuple(), once per column. For a fixed-length value passed by value it is two lines:
align the write position, then store the value.
if (att->attbyval)
{
/* pass-by-value */
data = (char *) att_nominal_alignby(data, att->attalignby);
store_att_byval(data, datum, att->attlen);
data_length = att->attlen;
}
src/backend/access/common/heaptuple.c, lines 360–366
Both tuples still start at lp_off 8152, though. A tuple’s start on the page
is rounded to a multiple of 8 (MAXALIGN, lesson 1), so the 36-byte tuple
takes 40 bytes of the page as well. For this pair, column order changes
lp_len and not the space used. It changes the space as soon as the padding
inside the tuple is bigger than the padding after it. Six columns, three
bool and three bigint, in two orders, 500 rows each:
CREATE TABLE mixed (a bool, b bigint, c bool, d bigint, e bool, f bigint) WITH (autovacuum_enabled = off);
CREATE TABLE
CREATE TABLE sorted (b bigint, d bigint, f bigint, a bool, c bool, e bool) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO mixed SELECT i % 2 = 0, i, i % 3 = 0, i * 2, i % 5 = 0, i * 3 FROM generate_series(1, 500) AS i;
INSERT 0 500
INSERT INTO sorted SELECT i, i * 2, i * 3, i % 2 = 0, i % 3 = 0, i % 5 = 0 FROM generate_series(1, 500) AS i;
INSERT 0 500
SELECT lp_len, lp_off FROM heap_page_items(get_raw_page('mixed', 0)) WHERE lp <= 2;
lp_len | lp_off
--------+--------
72 | 8120
72 | 8048
(2 rows)
SELECT count(*) AS rows_on_page_0 FROM heap_page_items(get_raw_page('mixed', 0));
rows_on_page_0
----------------
107
(1 row)
SELECT pg_relation_size('mixed') / 8192 AS pages;
pages
-------
5
(1 row)
SELECT lp_len, lp_off FROM heap_page_items(get_raw_page('sorted', 0)) WHERE lp <= 2;
lp_len | lp_off
--------+--------
51 | 8136
51 | 8080
(2 rows)
SELECT count(*) AS rows_on_page_0 FROM heap_page_items(get_raw_page('sorted', 0));
rows_on_page_0
----------------
136
(1 row)
SELECT pg_relation_size('sorted') / 8192 AS pages;
pages
-------
4
(1 row)
In mixed, each bool is followed by seven bytes of padding before the next
bigint: 3 × (1 + 7 + 8) = 48 bytes of data for 27 bytes of values, a 72-byte
tuple. In sorted, the bigints come first and the three bools fill
bytes 24–26 after them: 51 bytes, 56 on the page. With the 4-byte line
pointer that is 76 against 60 bytes a row, 107 against 136 rows on a page,
and 5 pages against 4 for the same 500 rows. The usual advice follows:
declare the 8-byte columns first, then the 4-byte ones, and so on down, with
the variable-length columns last.
The box below runs in your browser, in PGlite (PostgreSQL 19.0 compiled to
WebAssembly), on the same two tables. pg_column_size of a row value counts
the same 24-byte header and padding, so you can try other orders without
pageinspect:
SELECT pg_relation_size('mixed') / 8192 AS mixed_pages,
pg_relation_size('sorted') / 8192 AS sorted_pages;
SELECT pg_column_size(ROW(1::int, 2::bigint)) AS int_bigint,
pg_column_size(ROW(2::bigint, 1::int)) AS bigint_int; mixed_pages | sorted_pages
-------------+--------------
5 | 4
(1 row)
int_bigint | bigint_int
------------+------------
40 | 36
(1 row)A NULL takes no bytes
CREATE TABLE nulls (a bool, b bigint, c bool, d bigint, e bool, f bigint) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO nulls VALUES (true, 2, true, 4, true, 6) RETURNING xmin;
xmin
------
1101
(1 row)
INSERT 0 1
INSERT INTO nulls VALUES (true, NULL, true, 4, NULL, 6) RETURNING xmin;
xmin
------
1102
(1 row)
INSERT 0 1
SELECT lp, lp_len, t_infomask, t_hoff, t_bits, t_data
FROM heap_page_items(get_raw_page('nulls', 0));
lp | lp_len | t_infomask | t_hoff | t_bits | t_data
----+--------+------------+--------+----------+----------------------------------------------------------------------------------------------------
1 | 72 | 2048 | 24 | | \x010000000000000002000000000000000100000000000000040000000000000001000000000000000600000000000000
2 | 48 | 2049 | 24 | 10110100 | \x010100000000000004000000000000000600000000000000
(2 rows)
Row 1 has no NULLs, so no bitmap, t_infomask 2048 (HEAP_XMAX_INVALID
only) and the full 72 bytes. Row 2 has two: HEAP_HASNULL (1) is set, and
t_bits is the bitmap, one bit per column, column 1 first, 1 for a value
and 0 for NULL: 10110100 reads a, c, d and f present, b and e null. The
bitmap goes in byte 23, which was padding anyway, so t_hoff stays 24.
The NULL columns take no space at all, and that moves everything after them.
Without b, c no longer has a bigint before it, and lands at byte 1, right
after a. d then pads from 2 to 8. e is gone too, so f follows d
directly at 16. Row 2’s data is 24 bytes where row 1’s is 48. This is also
why a reader can never jump straight to column n of an arbitrary row:
where a column starts depends on which columns before it are present. A
reader checks the bitmap with:
/*
* Check a tuple's null bitmap to determine whether the attribute is null.
* Note that a 0 in the null bitmap indicates a null, while 1 indicates
* non-null.
*/
static inline bool
att_isnull(int ATT, const uint8 *BITS)
{
return !(BITS[ATT >> 3] & (1 << (ATT & 0x07)));
}
src/include/access/tupmacs.h, lines 23–32
With more than 8 columns the bitmap needs a second byte, and 23 + 2 rounds up to 32:
CREATE TABLE nine (c1 int, c2 int, c3 int, c4 int, c5 int, c6 int, c7 int, c8 int, c9 int) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO nine VALUES (NULL, 2, 3, 4, 5, 6, 7, 8, 9) RETURNING xmin;
xmin
------
1104
(1 row)
INSERT 0 1
SELECT lp_len, t_hoff, t_bits, t_data FROM heap_page_items(get_raw_page('nine', 0));
lp_len | t_hoff | t_bits | t_data
--------+--------+------------------+--------------------------------------------------------------------
64 | 32 | 0111111110000000 | \x0200000003000000040000000500000006000000070000000800000009000000
(1 row)
t_hoff is 32. The row is 64 bytes; with a value in c1 instead of the
NULL it would be 24 + 36 = 60, so here the NULL costs 4 bytes instead of
saving them. heap_form_tuple() computes t_hoff:
len = offsetof(HeapTupleHeaderData, t_bits);
if (hasnull)
len += BITMAPLEN(numberOfAttributes);
hoff = len = MAXALIGN(len); /* align user data safely */
src/backend/access/common/heaptuple.c, lines 1123–1128
offsetof(HeapTupleHeaderData, t_bits) is 23, the fixed header; BITMAPLEN
is (natts + 7) / 8. One bitmap byte fits in the padding up to 24; 2 to 9
bytes (9 to 72 columns) give 32.
One row of every type
CREATE TABLE every (b bool, s smallint, i int, l bigint, r real, d double precision,
dt date, ts timestamp, u uuid, t text) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO every VALUES (true, 7, 1000, 1234567890123, 1.5, -0.25, '2026-12-03', '2026-12-03 12:34:56.789', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'hello') RETURNING xmin;
xmin
------
1106
(1 row)
INSERT 0 1
SELECT lp_len, t_data FROM heap_page_items(get_raw_page('every', 0));
lp_len | t_data
--------+------------------------------------------------------------------------------------------------------------------------------------------------
94 | \x01000700e8030000cb04fb711f0100000000c03f00000000000000000000d0bf692600000000000008867cc1b8040300a0eebc999c0b4ef8bb6d6bb9bd380a110d68656c6c6f
(1 row)
SELECT unnest(tuple_data_split('every'::regclass, t_data, t_infomask,
t_infomask2, t_bits)) AS column_bytes
FROM heap_page_items(get_raw_page('every', 0));
column_bytes
------------------------------------
\x01
\x0700
\xe8030000
\xcb04fb711f010000
\x0000c03f
\x000000000000d0bf
\x69260000
\x08867cc1b8040300
\xa0eebc999c0b4ef8bb6d6bb9bd380a11
\x0d68656c6c6f
(10 rows)
tuple_data_split cuts t_data into the columns, using the table’s
descriptor. Laid out:
offset bytes column value
0 01 b bool true
1 00 padding
2 0700 s smallint 7
4 e8030000 i int 1000
8 cb04fb711f010000 l bigint 1234567890123
16 0000c03f r real 1.5 (IEEE 754 single)
20 00000000 padding
24 000000000000d0bf d double -0.25 (IEEE 754 double)
32 69260000 dt date 9833 days after 2000-01-01
36 00000000 padding
40 08867cc1b8040300 ts timestamp microseconds after 2000-01-01 00:00
48 a0eebc999c0b4ef8bb6d6bb9bd380a11 u uuid the 16 bytes as written
64 0d68656c6c6f t text 1-byte header, then "hello"
That is 70 bytes of data, 94 with the header, and 9 of them are padding.
Dates and timestamps count from 2000-01-01, not 1970. uuid is stored as
its 16 bytes in the order they are written, and its typalign is c, so it
needs no padding. Most of these values have a fixed size; the last one does
not.
Variable length: 1-byte and 4-byte headers
A varlena starts with a header that holds its total length, header included.
varatt.h describes the four forms by the low bits of the first byte (on a
little-endian machine):
* Bit layouts for varlena headers on little-endian machines:
*
* xxxxxx00 4-byte length word, aligned, uncompressed data (up to 1G)
* xxxxxx10 4-byte length word, aligned, *compressed* data (up to 1G)
* 00000001 1-byte length word, unaligned, TOAST pointer
* xxxxxxx1 1-byte length word, unaligned, uncompressed data (up to 126b)
*
* The "xxx" bits are the length field (which includes itself in all cases).
* In the big-endian case we mask to extract the length, in the little-endian
* case we shift. Note that in both cases the flag bits are in the physically
* first byte. Also, it is not possible for a 1-byte length word to be zero;
* this lets us disambiguate alignment padding bytes from the start of an
* unaligned datum. (We now *require* pad bytes to be filled with zero!)
src/include/varatt.h, lines 165–177
A value built in memory, from a literal or an expression, has the 4-byte
form; one copied out of another tuple may still have its 1-byte header.
fill_val() decides what is stored. A value that already has a 1-byte header is copied as it is; a 4-byte
one that is uncompressed and fits in 127 bytes, header included, is converted
to a 1-byte header. Neither is aligned. Anything else keeps its 4-byte header
and is aligned like any i value:
else if (VARATT_IS_SHORT(val))
{
/* no alignment for short varlenas */
data_length = VARSIZE_SHORT(val);
memcpy(data, val, data_length);
}
else if (att->attispackable && VARATT_CAN_MAKE_SHORT(val))
{
/* convert to short varlena -- no alignment */
data_length = VARATT_CONVERTED_SHORT_SIZE(val);
SET_VARSIZE_SHORT(data, data_length);
memcpy(data + 1, VARDATA(val), data_length - 1);
}
else
{
/* full 4-byte header varlena */
data = (char *) att_nominal_alignby(data, att->attalignby);
data_length = VARSIZE(val);
memcpy(data, val, data_length);
}
src/backend/access/common/heaptuple.c, lines 395–414
The boundary is easy to see. Two rows of (flag bool, body text), with 126
and 127 as:
CREATE TABLE notes (flag bool, body text) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO notes VALUES (true, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') RETURNING xmin;
xmin
------
1108
(1 row)
INSERT 0 1
INSERT INTO notes VALUES (true, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') RETURNING xmin;
xmin
------
1109
(1 row)
INSERT 0 1
SELECT lp, lp_len, substr(t_data, 1, 8) AS first_8_bytes
FROM heap_page_items(get_raw_page('notes', 0));
lp | lp_len | first_8_bytes
----+--------+--------------------
1 | 152 | \x01ff616161616161
2 | 159 | \x010000000c020000
(2 rows)
SELECT length(body), pg_column_size(body) FROM notes;
length | pg_column_size
--------+----------------
126 | 127
127 | 131
(2 rows)
With 126 bytes the total is 127, the most a 1-byte header can hold: ff is
(127 << 1) | 1, right after the bool at byte 1. With 127 bytes the total is
131, so the value keeps its 4-byte header, which is aligned to 4: bytes 1–3
are padding and the header 0c020000 is 0x20c = 131 « 2. The tuple grows
from 152 to 159 bytes for one more character.
Reading needs a trick. The writer knew which form each value got, but the
reader only has the bytes, and an unaligned 1-byte header and an aligned
4-byte one start at different offsets. The reader looks at the byte where it
is: padding is always zero, and a 1-byte header never is, since its low bit
is set. So a zero byte means “align first”, anything else means “the value
starts here”. The comment is on att_align_pointer(); nocachegetattr(),
which fetches one column of a heap tuple, uses its twin below it,
att_pointer_alignby(), which takes the alignment in bytes.
heap_deform_tuple(), which reads all of them, makes the same choice inline
in align_fetch_then_add(): it aligns unless the byte has a 1-byte header’s
low bit set.
/*
* att_align_pointer performs the same calculation as att_align_datum,
* but is used when walking a tuple. attptr is the current actual data
* pointer; when accessing a varlena field we have to "peek" to see if we
* are looking at a pad byte or the first byte of a 1-byte-header datum.
* (A zero byte must be either a pad byte, or the first byte of a correctly
* aligned 4-byte length word; in either case we can align safely. A non-zero
* byte must be either a 1-byte length word, or the first byte of a correctly
* aligned 4-byte length word; in either case we need not align.)
*
* Note: some callers pass a "char *" pointer for cur_offset. This is
* a bit of a hack but should work all right as long as uintptr_t is the
* correct width.
*/
#define att_align_pointer(cur_offset, attalign, attlen, attptr) \
( \
((attlen) == -1 && VARATT_NOT_PAD_BYTE(attptr)) ? \
(uintptr_t) (cur_offset) : \
att_align_nominal(cur_offset, attalign) \
)
/*
* Similar to att_align_pointer, but accepts a number of bytes, typically from
* CompactAttribute.attalignby to align the pointer by.
*/
#define att_pointer_alignby(cur_offset, attalignby, attlen, attptr) \
( \
((attlen) == -1 && VARATT_NOT_PAD_BYTE(attptr)) ? \
(uintptr_t) (cur_offset) : \
TYPEALIGN(attalignby, cur_offset))
src/include/access/tupmacs.h, lines 359–388
STORAGE PLAIN tells TOAST to leave a column alone, and the packing test in
fill_val() above (attispackable) is false for it. Yet:
CREATE TABLE packed (body text) WITH (autovacuum_enabled = off);
CREATE TABLE
CREATE TABLE plain (body text STORAGE PLAIN) WITH (autovacuum_enabled = off);
CREATE TABLE
INSERT INTO packed VALUES ('hello') RETURNING xmin;
xmin
------
1112
(1 row)
INSERT 0 1
INSERT INTO plain VALUES ('hello') RETURNING xmin;
xmin
------
1113
(1 row)
INSERT 0 1
SELECT lp_len, t_data FROM heap_page_items(get_raw_page('packed', 0));
lp_len | t_data
--------+----------------
30 | \x0d68656c6c6f
(1 row)
SELECT lp_len, t_data FROM heap_page_items(get_raw_page('plain', 0));
lp_len | t_data
--------+----------------
30 | \x0d68656c6c6f
(1 row)
Both rows got a 1-byte header. A comment in heaptuple.c predicts exactly
this:
/*
* Does att's datatype allow packing into the 1-byte-header varlena format?
* While functions that use TupleDescAttr() and assign attstorage =
* TYPSTORAGE_PLAIN cannot use packed varlena headers, functions that call
* TupleDescInitEntry() use typeForm->typstorage (TYPSTORAGE_EXTENDED) and
* can use packed varlena headers, e.g.:
* CREATE TABLE test(a VARCHAR(10000) STORAGE PLAIN);
* INSERT INTO test VALUES (repeat('A',10));
* This can be verified with pageinspect.
*/
#define ATT_IS_PACKABLE(att) \
((att)->attlen == -1 && (att)->attstorage != TYPSTORAGE_PLAIN)
src/backend/access/common/heaptuple.c, lines 75–86
The tuple an INSERT stores is built from the row the plan produced, and that
row’s descriptor takes attstorage from the type (x for text), not from
the column. That is my reading of the executor, not a traced call path:
ExecGetInsertNewTuple() in nodeModifyTable.c copies the plan’s row into a
slot of the table’s kind, and that copy calls heap_form_tuple() with the
plan slot’s descriptor (tts_virtual_copy_heap_tuple() in execTuples.c). Where
PLAIN does stop the 1-byte header is a tuple formed with the table’s own
descriptor, and the next lesson meets one: the chunks of a TOAST table.
tinypg: thirteen types and fill_val()
tinypg’s state at tag lesson-02 adds types.py, the four pg_type columns
for each type it knows and how to turn a Python value into the stored bytes:
Type("bool", 1, True, "c", "p", lambda v: bytes([1 if v else 0]), lambda b: b[0] != 0),
Type("int2", 2, True, "s", "p", *_fixed("h")),
Type("int4", 4, True, "i", "p", *_fixed("i")),
Type("int8", 8, True, "d", "p", *_fixed("q")),
Type("float4", 4, True, "i", "p", *_fixed("f")),
Type("float8", 8, True, "d", "p", *_fixed("d")),
Type("oid", 4, True, "i", "p", *_fixed("I")),
Type("date", 4, True, "i", "p", _date_encode, _date_decode),
Type("timestamp", 8, True, "d", "p", _ts_encode, _ts_decode),
Type("uuid", 16, False, "c", "p", lambda v: v.bytes, lambda b: uuid.UUID(bytes=bytes(b))),
Type("text", -1, False, "i", "x", lambda v: v.encode("utf-8"), lambda b: bytes(b).decode("utf-8")),
Type("varchar", -1, False, "i", "x", lambda v: v.encode("utf-8"), lambda b: bytes(b).decode("utf-8")),
Type("bytea", -1, False, "i", "x", bytes, bytes),
A test checks every row of this table against the pg_type rows the
recording script saved. varatt.py has the header forms, for example:
def can_make_short(datum):
"""VARATT_CAN_MAKE_SHORT(): uncompressed, and the data plus a 1-byte
header fits in 127 bytes."""
return is_4b_u(datum) and varsize_4b(datum) - VARHDRSZ + VARHDRSZ_SHORT <= VARATT_SHORT_MAX
def make_short(datum):
"""SET_VARSIZE_SHORT() plus the copy fill_val() does: the same data
behind a 1-byte header, (total size << 1) | 1."""
data = datum[VARHDRSZ:varsize_4b(datum)]
return bytes([(len(data) + VARHDRSZ_SHORT) << 1 | 0x01]) + bytes(data)
fill_val() is the C function’s three cases, plus a return value that says
where the value went, which the figure below is drawn from:
def fill_val(data, datum, att):
"""fill_val(): append one non-null value to the data area.
Returns how it was stored: (start of any padding, start of the value,
end, form), the form being "fixed", "1b", "1b-converted" or "4b".
"""
pad_from = len(data)
if att.type.len > 0: # fixed length
form = "fixed"
data += bytes(align(len(data), ALIGN[att.type.align]) - len(data))
elif varatt.is_short(datum): # already short: no alignment
form = "1b"
elif att.storage != "p" and varatt.can_make_short(datum):
form, datum = "1b-converted", varatt.make_short(datum) # no alignment
else: # 4-byte header, aligned
form = "4b"
data += bytes(align(len(data), ALIGN[att.type.align]) - len(data))
start = len(data)
data += datum
return pad_from, start, len(data), form
tinypg/heaptuple.py, lines 75–94
Reading peeks at the byte as att_pointer_alignby() does:
if att.type.len > 0:
off = align(off, ALIGN[att.type.align])
values.append(att.type.decode(data[off:off + att.type.len]))
off += att.type.len
continue
if data[off] == 0: # a pad byte: align
off = align(off, ALIGN[att.type.align])
datum = data[off:]
values.append(att.type.decode(varatt.vardata_any(datum)))
off += varatt.varsize_any(datum)
return values
tinypg/heaptuple.py, lines 176–186
And to match the STORAGE PLAIN row, tinypg’s INSERT forms its tuple as the
server’s does, with each type’s own storage:
def __init__(self, path, types):
self.path = path
self.desc = make_desc(types)
# An INSERT forms its tuple from the plan's output row, whose
# descriptor takes attstorage from pg_type rather than from the
# column, so even a STORAGE PLAIN column gets 1-byte headers (the
# comment above ATT_IS_PACKABLE in heaptuple.c gives this example).
self.insert_desc = [a._replace(storage=a.type.storage) for a in self.desc]
tinypg/heapfile.py, lines 17–24
A heap tuple drawn to scale as a strip of bytes: the 23-byte header, then each column placed where fill_val puts it, with dashed padding before columns that need alignment; first (int, bigint), then (bigint, int), then a row with two NULLs. (This figure steps through a recorded run; it needs JavaScript.)
tinypg placing each column of three recorded rows, from python3 -m tinypg trace-layout tests/fixtures/pg19_layout.json ib bi nulls:2 (tag
lesson-02). Ticks every 8 bytes; dashed boxes are padding. The last frame
of each row compares the length with the lp_len PostgreSQL recorded.
The comparison replays every recorded INSERT, with the server’s xids, into
ten tinypg tables and compares the 17 pages with the ones get_raw_page
returned:
$ python3 -m tinypg compare tests/fixtures/pg19_layout.json
ib (a int4, b int8): 1 INSERTs, 1 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 1 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000058d4a103, tinypg 0000000000000000; 4 bytes differ
bi (b int8, a int4): 1 INSERTs, 1 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 1 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000c8d4a103, tinypg 0000000000000000; 4 bytes differ
mixed (a bool, b int8, c bool, d int8, e bool, f int8): 1 INSERTs, 500 rows; PostgreSQL wrote 5 pages, tinypg 5
block 0: 107 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 000000004861a203, tinypg 0000000000000000; 4 bytes differ
block 1: 107 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000028ada203, tinypg 0000000000000000; 4 bytes differ
block 2: 107 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000b8d8a203, tinypg 0000000000000000; 4 bytes differ
block 3: 107 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 000000006004a303, tinypg 0000000000000000; 4 bytes differ
block 4: 72 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000b821a303, tinypg 0000000000000000; 4 bytes differ
sorted (b int8, d int8, f int8, a bool, c bool, e bool): 1 INSERTs, 500 rows; PostgreSQL wrote 4 pages, tinypg 4
block 0: 136 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000b850a303, tinypg 0000000000000000; 4 bytes differ
block 1: 136 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000907fa303, tinypg 0000000000000000; 4 bytes differ
block 2: 136 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000080aea303, tinypg 0000000000000000; 4 bytes differ
block 3: 92 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000038cea303, tinypg 0000000000000000; 4 bytes differ
nulls (a bool, b int8, c bool, d int8, e bool, f int8): 2 INSERTs, 2 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 2 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000068e6a303, tinypg 0000000000000000; 4 bytes differ
nine (c1 int4, c2 int4, c3 int4, c4 int4, c5 int4, c6 int4, c7 int4, c8 int4, c9 int4): 1 INSERTs, 1 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 1 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000e001a403, tinypg 0000000000000000; 4 bytes differ
every (b bool, s int2, i int4, l int8, r float4, d float8, dt date, ts timestamp, u uuid, t text): 1 INSERTs, 1 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 1 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 000000004853a403, tinypg 0000000000000000; 4 bytes differ
notes (flag bool, body text): 2 INSERTs, 2 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 2 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 000000003880a403, tinypg 0000000000000000; 4 bytes differ
packed (body text): 1 INSERTs, 1 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 1 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 0000000040dca403, tinypg 0000000000000000; 4 bytes differ
plain (body text STORAGE PLAIN): 1 INSERTs, 1 rows; PostgreSQL wrote 1 pages, tinypg 1
block 0: 1 tuples, 8188 of 8192 bytes identical
pd_lsn (bytes 0-7): postgres 00000000a8dca403, tinypg 0000000000000000; 4 bytes differ
Every page is identical except the low half of pd_lsn, which needs a
write-ahead log tinypg does not have yet. That includes the 1,000 rows of
mixed and sorted, the null bitmaps, the 4-byte header with its padding,
and the STORAGE PLAIN row. tinypg also reads the server’s own file:
$ python3 -m tinypg inspect "$PGDATA/base/16420/25393" --types bool,int2,int4,int8,float4,float8,date,timestamp,uuid,text
block 0: lsn 0/03A45348 checksum 2850 flags 0 lower 28 upper 8096 special 8192 pagesize_version 8196 prune_xid 1106
lp off len xmin xmax ctid infomask2 infomask hoff row
1 8096 94 1106 0 (0,1) 10 2050 24 (true, 7, 1000, 1234567890123, 1.5, -0.25, '2026-12-03', '2026-12-03 12:34:56.789', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'hello')
What tinypg leaves out: numeric (a varlena of base-10000 digits with its
own header), arrays, composite and range types, name and char(n), and
compressed or out-of-line values, which are the next lesson. PostgreSQL also
caches the offset of each fixed-length column up to the first variable-length
one (attcacheoff), so that it can read those directly; tinypg always walks
from the first column.
Try it yourself
With a PostgreSQL 19 server, pageinspect, and tables created WITH (autovacuum_enabled = off):
Reorder the columns of
everyasl, d, ts, u, i, r, dt, s, b, t(8-byte types first, then 16-byteuuid, then 4, 2 and 1, thentext). Predictlp_len, then check it, or checkpg_column_size(ROW(...))in the box above.Answer
85: 24 + 8 + 8 + 8 + 16 + 4 + 4 + 4 + 2 + 1 + 6 with no padding at all, so it takes 88 bytes on the page against 96 for the original order.
pg_column_sizeof the row value gives 85 too.A table
(s smallint, t text)gets the row(7, repeat('x', 200)). Where does the text’s header start, and what islp_len?Answer
The
smallinttakes bytes 0–1. 200 bytes do not fit a 1-byte header, so the value keeps its 4-byte header, aligned to 4: bytes 2–3 are padding, the header is at 4 ((204 << 2)=0x330, stored30030000), andlp_lenis 24 + 4 + 204 = 232.How many columns can a table have before a row with a NULL needs
t_hoff40?Answer
t_hoffisMAXALIGN(23 + (natts + 7) / 8): 24 up to 8 columns, 32 up to 72, and 40 from 73 columns (a 10-byte bitmap). tinypg’sform_tuplegives the same for 8, 9, 72 and 73 columns.Insert
''(the empty string) into atextcolumn. What is stored, and how does the reader know it is not a pad byte?Answer
One byte,
03: a 1-byte header with total length 1,(1 << 1) | 1. It is not zero, so the reader does not align, and the value is the zero bytes after the header.
The tinypg side, once the repository is public:
git clone https://github.com/toothywalrus/tinypg && cd tinypg
git checkout lesson-02
python3 -m unittest
python3 -m tinypg compare tests/fixtures/pg19_layout.json
python3 -m tinypg trace-layout tests/fixtures/pg19_layout.json ib bi nulls:2
To record your own: tools/record_tuple_layout.py --out DIR with the usual
PGHOST, PGPORT, PGUSER and PGDATABASE. It drops and recreates the ten
tables it uses.
Sources
All PostgreSQL code is quoted from tag
REL_19_0 (commit
5c839a2a08b9), with tabs expanded to four spaces and the common indentation
removed.
src/include/catalog/pg_type.h:typlen,typbyval,typalign,typstoragesrc/backend/access/common/heaptuple.c:heap_form_tuple(),heap_compute_data_size(),fill_val(),ATT_IS_PACKABLEsrc/include/access/tupmacs.h:att_isnull(), the alignment macrossrc/include/varatt.h: varlena header forms,VARATT_CAN_MAKE_SHORTsrc/include/access/htup_details.h:BITMAPLEN, the infomask bitssrc/backend/executor/nodeModifyTable.c,src/backend/executor/execTuples.c:ExecGetInsertNewTuple(),tts_virtual_copy_heap_tuple()contrib/pageinspect/:heap_page_items,tuple_data_split- tinypg at
lesson-02: the code, the fixturetests/fixtures/pg19_layout.json, andtools/record_tuple_layout.py, which recorded every psql and shell output on this page
ls postgres-internals/
Storage
- 01 A table is a file of 8 KB pages draftWhere a table lives on disk, the page header, line pointers, tuples filling from the end, and what a ctid is.
- 02 Inside a tuple: alignment, nulls and varlena draftHow column values are laid out after the header, why column order changes a row's size, and the 1-byte and 4-byte length headers.
- 03 TOAST: values too big for a page draftCompression, out-of-line storage in a TOAST table, and the 2 KB threshold that triggers them.
- 04 The free space map draftThe _fsm fork: a tree of one-byte free-space categories that tells an INSERT which page has room.
Buffers and durability
- 05 Shared buffers: a page cache with pins and locks plannedThe buffer table, buffer descriptors, pins, content locks, and clock-sweep eviction.
- 06 The write-ahead log: records and LSNs plannedWAL record layout, pd_lsn, and the rule that a page may not reach disk before its log does.
- 07 Checkpoints, full-page writes and checksums plannedWhat a checkpoint guarantees, why the first change after one logs the whole page, and how pd_checksum is computed.
- 08 Crash recovery: replaying the log plannedStarting from the last checkpoint's redo point and replaying records whose LSN is newer than the page's.
MVCC
- 09 Transaction IDs and the commit log plannedAssigning xids, and pg_xact: two bits of commit status per transaction.
- 10 xmin, xmax and the life of a row version plannedWhat UPDATE and DELETE really write, and following ctid chains to the newest version.
- 11 Snapshots: what a transaction can see plannedxmin, xmax and the in-progress list, and when READ COMMITTED and REPEATABLE READ take them.
- 12 Visibility rules and hint bits plannedHeapTupleSatisfiesMVCC case by case, and why reading a row can write to its page.
- 13 HOT updates and page pruning plannedHeap-only tuples, redirect line pointers, and cleaning a page while reading it.
- 14 VACUUM: removing dead tuples plannedScanning the heap, cleaning indexes, and marking line pointers unused.
- 15 The visibility map plannedThe _vm fork's all-visible and all-frozen bits, and what index-only scans and VACUUM get from them.
- 16 Freezing and transaction ID wraparound plannedWhy 32-bit xids wrap around, what freezing writes, and multixacts.
Indexes
- 17 B-tree pages and the Lehman–Yao tree plannedSpecial space, high keys and right links: a B-tree you can search while it changes.
- 18 B-tree insertion and page splits plannedDescending the tree, choosing a split point, and finishing a split in the parent.
- 19 Deduplication and bottom-up deletion plannedPosting lists for duplicate keys, and deleting old versions before a page has to split.
- 20 Hash indexes plannedBuckets, overflow pages and linear-hashing splits.
- 21 GIN and GiST, briefly plannedAn inverted index and a balanced tree of predicates: what each stores and when each fits.
Queries
- 22 From text to parse tree plannedThe grammar, the raw parse tree, and why parsing needs no catalog.
- 23 Analysis and rewriting plannedResolving names against the catalog, the Query tree, and the rewriter's views and rules.
- 24 The planner: paths and the cost model plannedseq_page_cost, random_page_cost and cpu_tuple_cost, and how the cheapest path wins.
- 25 Statistics and selectivity plannedWhat ANALYZE samples, most common values, histograms, and estimating a WHERE clause.
- 26 Join algorithms and join order plannedNested loop, hash and merge joins, and searching the join orders.
- 27 The executor: Volcano-style iterators plannedPlan nodes that each return one row per call, from a sequential scan up to a sort.
Concurrency and the server
- 28 Locks: heavyweight, row-level and lightweight plannedThe lock manager, row locks stored in xmax, LWLocks and spinlocks, and deadlock detection.
- 29 Processes and shared memory plannedThe postmaster, one backend per connection, the background workers, and what they share.
- 30 Streaming replication plannedShipping WAL to a standby, replaying it there, and replication slots.