Sub topic 1
Where a table lives on disk: files, segments, and forks
Prerequisites
This chapter assumes you know basic SQL (CREATE TABLE, INSERT, SELECT), can use psql, and understand that files store bytes on disk. You do not need prior knowledge of PostgreSQL internals.
Files, segments, and forks
PostgreSQL stores each table as one or more operating system files in the data directory. The file name comes from the table's relfilenode, a number that is often close to the table's OID. Run this to find the path:
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance numeric);
INSERT INTO accounts VALUES (1, 'alice', 100), (2, 'bob', 200);
SELECT pg_relation_filepath('accounts');The result is a relative path such as base/16384/16390.
When a table file reaches 1 GB, PostgreSQL starts a new segment. The first segment has no suffix. Later segments are named 16390.1, 16390.2, and so on.
Each table also has forks, which are separate files with a suffix. The main fork holds the rows. The _fsm fork holds the free space map, and the _vm fork holds the visibility map.
Pages: the 8 KB unit of storage
PostgreSQL reads and writes table data in fixed-size blocks called pages. The default page size is 8 KB (8192 bytes). Check it with SHOW block_size;. A table's page count is pg_relation_size('accounts') / current_setting('block_size')::int.
Inside a heap page
A heap page is the page type that stores table rows. Each page has four parts:
- Page header: 24 bytes at the start. It includes
pd_lowerandpd_upper, which mark the edges of the free space. - Line pointers: 4-byte entries that follow the header.
- Free space: the unused gap between the line pointers and the tuples.
- Tuples: the row data, packed from the end of the page.
Line pointers and ctid: how a row is addressed
Each row is identified by its ctid, a pair of (block number, line pointer number). Block numbers start at 0, and line pointer numbers start at 1.
SELECT ctid, * FROM accounts;You might see (0,1) for the first row and (0,2) for the second, which means both rows sit on block 0.
> The ctid is a physical location, not a permanent key. It changes when an UPDATE writes a new row version or when VACUUM FULL rewrites the table.
Exercise
After you run UPDATE accounts SET balance = 150 WHERE id = 1;, why does the ctid of that row change?
Show answer
UPDATE writes a new row version in a new location and leaves the old version in place until VACUUM removes it. The new version therefore has a different ctid.