PostgreSQL

The PostgreSQL storage format

How PostgreSQL lays a table out on disk, from the data directory down to one column's bytes, and how MVCC shows up in them. The examples are read from the sample table, written by PostgreSQL 19.0.

Files: relations and forks

Each table, index, sequence and materialized view is a relation, stored in its own files under the data directory: base/<database oid>/<relfilenode>. SELECT pg_relation_filepath('my_table') gives the path. The relfilenode starts out equal to the table's OID but changes whenever the table is rewritten (TRUNCATE, VACUUM FULL, CLUSTER, some ALTER TABLEs). A file grows to 1 GB, then continues in <relfilenode>.1, .2 and so on.

Beside the main file are its forks: _vm, the visibility map, and _fsm, the free space map, both described below; unlogged tables also have _init. A table with long values has a TOAST table of its own, with its own relfilenode.

Unlike a SQLite or InnoDB file, a relation file does not say what its columns are. That is in the system catalog, pg_attribute. The viewer asks for the columns, and gives a query that lists them.

PostgreSQL writes changes to the WAL first and to the relation files later, at a checkpoint, so a file copied from a running server may be missing recent changes. Run CHECKPOINT first, or copy it while the server is stopped. (Database file layout.)

Pages

Every file is an array of 8 KB blocks (pages), numbered from 0. All integers are in the machine's byte order, little-endian on nearly every server. Each page starts with a 24-byte header:

00–7: pd_lsnpd_lsn8–9: pd_checksum810–11: pd_flags1012–13: pd_lower1214–15: pd_upper1416–17: pd_special1618–19: pd_pagesize_version1820–23: pd_prune_xidpd_prune_xid
OffsetFieldWhat it is for
0pd_lsnThe WAL position of the last change to this page. The page may not be written to disk until the WAL is flushed up to here.
8pd_checksumA 16-bit checksum of the page and its block number, when the cluster has data checksums on; otherwise 0.
10pd_flagsHints: free line pointers, page full, all visible.
12pd_lowerWhere the line pointer array ends, and free space begins.
14pd_upperWhere the tuples begin, and free space ends.
16pd_specialWhere the special space begins: index pages keep their own data there; for a heap page it is the end of the page.
18pd_pagesize_versionThe page size ORed with the layout version, 4 since PostgreSQL 8.3.
20pd_prune_xidThe oldest transaction that left something prunable on this page, or 0: a hint for opportunistic pruning.

After the header comes an array of 4-byte line pointers, growing forwards; the tuples are packed from the end of the page backwards; the free space is between them, from pd_lower to pd_upper. Index pages also have a special space at the very end.

pd_lower →← pd_upperheaderline pointers →free spacetuple 3tuple 2tuple 108191

A line pointer holds the tuple's offset and length and one of four states: normal, unused, dead (pruned, but an index may still point to it) or redirect. A row's address, its ctid, is (block, line pointer number), so PostgreSQL can move a tuple within its page, when it compacts the page, without changing its address or any index entry.

Tuples

A heap tuple has a 23-byte header, then a null bitmap if any column is NULL (one bit per column, 1 meaning present), then padding to a multiple of 8, then the columns:

OffsetFieldWhat it is for
0t_xminThe transaction that inserted this version.
4t_xmaxThe transaction that deleted or updated it, or locked it; 0 if none.
8t_cidThe command number within the transaction (or t_xvac, for old VACUUM FULL).
12t_ctidThis tuple's own address (block, item), or the next version's if it was updated.
18t_infomask2The number of columns (low 11 bits) and the HOT flags.
20t_infomaskFlags: nulls, variable widths, TOAST, and hint bits about xmin and xmax.
22t_hoffWhere the column data starts: the header, the null bitmap, then padding to 8 bytes.

Here is a row from block 0 of the sample, item 1; lyrics is NULL, which costs only a 0 bit:

OffsetPartBytes
7912t_xmin9a 02 00 00
7916t_xmax00 00 00 00
7920t_cid00 00 00 00
7924t_ctid00 00 00 00 01 00
7930t_infomask213 00
7932t_infomask03 09
7934t_hoff20
7935null bitmap: 1111111111111111110ff ff 03
7944id (integer): 101 00 00 00
7948album_id (smallint): 101 00
7950name (text): Track 111 54 72 61 63 6b 20 31
7958composer (character varying(120)): Composer 117 43 6f 6d 70 6f 73 65 72 20 31
7969genre (text): jazz0b 6a 61 7a 7a
7974padding00 00
7976ms (integer): 127919af f3 01 00
7980price (numeric(5,2)): 1.290f 00 81 01 00 54 0b
7987padding00
7988rating (real): 0.1cd cc cc 3d
7992score (double precision): 0.1428571428571428592 24 49 92 24 49 c2 3f
8000explicit (boolean): f00
8001padding00 00 00
8004released (date): 1960-01-08f5 c6 ff ff
8008added (timestamp without time zone): 2024-01-01 00:01:01.00798 24 8c d8 d5 b0 02 00
8016played (timestamp with time zone): 2024-06-01 13:00:00+0000 94 49 72 d2 bc 02 00
8024length (interval): 00:01:0140 c9 a2 03 00 00 00 00 00 00 00 00 00 00 00 00
8040uid (uuid): c4ca4238-a0b9-2382-0dcc-509a6f75849bc4 ca 42 38 a0 b9 23 82 0d cc 50 9a 6f 75 84 9b
8056plays (bigint): 10000000303 e1 f5 05 00 00 00 00
8064tags (text[]): {t1,"x y"}4b 01 00 00 00 00 00 00 00 19 00 00 00 02 00 00 00 01 00 00 …
8101meta (jsonb): {"f": 0.25000000000000000000, "n": 1, "oad 04 00 00 20 01 00 00 80 01 00 00 00 02 00 00 00 04 00 00 …

Columns are stored in order, each aligned to its type's alignment (1, 2, 4 or 8 bytes), so column order affects a table's size: a smallint before a bigint wastes 6 bytes of padding. Variable-length values (text, numeric, jsonb, arrays…) start with a length header of 1 byte when they are under 127 bytes, and of 4 bytes otherwise; a 1-byte header is not aligned.

MVCC in the bytes

PostgreSQL never updates a row in place. An UPDATE writes a new version and sets the old version's t_xmax to the updating transaction; a DELETE only sets t_xmax. Every transaction decides which versions it can see from t_xmin, t_xmax and its snapshot. Old versions stay on the page until VACUUM removes them, once no running transaction could still need them.

To know whether t_xmin committed, a reader looks it up in pg_xact, then records the answer in hint bits in t_infomask (XMIN_COMMITTED, XMIN_INVALID, and the same for xmax) so the next reader does not have to. That is why a plain SELECT can dirty pages. Both XMIN bits together mean frozen: the row is older than any transaction, and its xmin no longer matters, which protects it from transaction id wraparound.

BitNameMeaning
t_infomask 0x0001HASNULLhas a null bitmap
t_infomask 0x0002HASVARWIDTHhas variable-width columns
t_infomask 0x0004HASEXTERNALhas values stored in the TOAST table
t_infomask 0x0008HASOID_OLDhas an OID (tables WITH OIDS, before PostgreSQL 12)
t_infomask 0x0010XMAX_KEYSHR_LOCKxmax holds FOR KEY SHARE
t_infomask 0x0020COMBOCIDt_cid is a combo command id
t_infomask 0x0040XMAX_EXCL_LOCKxmax holds an exclusive lock
t_infomask 0x0080XMAX_LOCK_ONLYxmax only locked the row; it did not delete or update it
t_infomask 0x0100XMIN_COMMITTEDhint: the inserting transaction committed
t_infomask 0x0200XMIN_INVALIDhint: the inserting transaction aborted
t_infomask 0x0400XMAX_COMMITTEDhint: the deleting transaction committed
t_infomask 0x0800XMAX_INVALIDhint: xmax is not a live deleter (aborted, or none)
t_infomask 0x1000XMAX_IS_MULTIxmax is a MultiXactId (several lockers)
t_infomask 0x2000UPDATEDthis is the new version written by an UPDATE
t_infomask 0x4000MOVED_OFFmoved by a pre-9.0 VACUUM FULL
t_infomask 0x8000MOVED_INmoved by a pre-9.0 VACUUM FULL
t_infomask2 0x2000KEYS_UPDATEDdeleted, or updated in a key column
t_infomask2 0x4000HOT_UPDATEDupdated in place (HOT): the new version is on this page and no index points to it
t_infomask2 0x8000HEAP_ONLY_TUPLEa heap-only tuple: no index entry points here; reach it through the HOT chain

Of the sample's 2,848 tuples, 2,607 are live and 241 are versions deleted or replaced since the last VACUUM.

HOT updates

If an UPDATE changes no indexed column and the new version fits on the same page, PostgreSQL writes a heap-only tuple (HOT): no index entries are added, the old version gets HOT_UPDATED, and its t_ctid points to the new one. An index scan arrives at the first version and follows the chain. When the page is pruned, the dead versions at the start of the chain are removed and their line pointer becomes a redirect to the first surviving one, so the index entry still leads somewhere.

In block 0 of the sample:

  1. line pointer 10 is a redirect to 25
  2. item 25: heap-only tuple, xmin 676, the current version

A table with a fillfactor below 100 leaves room on each page so that updates can stay HOT.

How values are stored

TypeStored as
smallint, integer, bigint2, 4 or 8 bytes, aligned to their size, in the machine's byte order.
real, double precisionIEEE 754, 4 or 8 bytes.
boolean, "char"One byte.
numericVariable length: a sign, a display scale and a weight, then base-10000 digits, 2 bytes each. Small values use a 2-byte header instead of 4.
text, varchar, char(n), byteaA length header and the bytes; char(n) keeps its padding spaces.
date4 bytes: days since 2000-01-01.
timestamp, timestamptz8 bytes: microseconds since 2000-01-01 00:00 (UTC for timestamptz).
time, timetz, intervalMicroseconds; timetz adds the zone offset (4 bytes), interval adds days and months (4 bytes each).
uuid16 bytes.
jsonbA binary tree of containers: counts and offsets first, then keys (sorted by length, then bytes) and values.
arraysDimensions, lower bounds, the element type's OID, an optional null bitmap, then the elements.

TOAST

A tuple must fit on a page, and PostgreSQL tries to keep it under about 2 KB. A longer row's variable-length values are first compressed in place (with pglz, or lz4 if default_toast_compression says so), and if that is not enough they are moved out to the table's TOAST table in chunks of about 2 KB, leaving an 18-byte pointer in the row. A column's STORAGE setting chooses which of these may happen. (TOAST.)

Row 41 of the sample keeps its lyrics this way: an 18-byte pointer to value 16452 in TOAST table 16448, 2,560 bytes, in 2 chunks.

B-tree indexes

An index is a relation of its own. Block 0 of a B-tree is its metapage, which says where the root is. Every other page ends in a 16-byte special space with its left and right siblings, its level (0 for leaves) and flags. Leaf tuples are a 6-byte heap TID, a 2-byte size and flags, and the key; internal pages hold pivot keys whose TID field is a downlink to a child block.

Each page except the rightmost on its level begins with a high key: an upper bound for the page, used by searches racing with a split. On internal pages, the first real item has no key at all: it stands for "minus infinity". Since PostgreSQL 12, pivots keep only as many key columns as they need to separate their neighbours (suffix truncation), plus a heap TID when even the full key does not; since 13, duplicates on a leaf are merged into one tuple with a posting list of heap TIDs (deduplication).

In the sample's index on genre, which has six distinct values for 2,848 rows, block 1 holds the key blues once, with a posting list of 121 heap TIDs, instead of 121 separate tuples. The whole index is 5 blocks; the primary key, whose keys are all different, is 11.

The sample's index on lpad(id::text, 200, 'x') has 200-byte keys, so only a few dozen fit on a page and the tree is 3 levels deep. Open the sample and pick tracks_long to walk it.

The visibility map

The _vm fork keeps two bits for each heap block: all visible, set by VACUUM when every tuple on the block is visible to everyone, and all frozen. An index-only scan skips the heap for all-visible blocks, and VACUUM skips them; an anti-wraparound VACUUM skips only the all-frozen ones. Any change to a block clears its bits. In the sample, 2 of 130 blocks are marked all visible, because the last updates came after the last VACUUM.

The free space map

The _fsm fork records one byte per heap block: its free space in steps of 32 bytes. Each FSM page is a binary tree stored in an array, where each parent holds the maximum of its children, and the pages themselves form a three-level tree, so INSERT can find a block with enough room in a few reads. It is updated by VACUUM, so it is approximate. (Free space map.)

Checksums

When the cluster has data checksums on (the default since PostgreSQL 18), pd_checksum holds a 16-bit checksum of the page, computed with the field itself as zero and mixed with the block number, so a block written to the wrong place is caught too. The viewer checks every block.