Sub topic 1
Where a table lives on disk: files, segments, and forks
Every PostgreSQL table is stored in ordinary files in the server's data directory. This chapter shows how to find those files and how big tables are split across several files. It also covers the extra files that sit beside each table. Later chapters open the main file and look at the pages inside it. Here we stay at the level of file names, sizes, and layout.
Prerequisites
This chapter assumes you have:
- Basic SQL:
CREATE TABLE,INSERT,SELECT. - Some comfort with
psqland running meta-commands and queries. - A general idea of what a transaction is.
- A basic picture of files, directories, and bytes on disk.
To follow along, you need a PostgreSQL 14 or later server that you can connect to. Looking at the files themselves with ls needs shell access to the server machine, but the SQL examples work without it.
The data directory
A PostgreSQL server keeps all of its persistent state under one directory, the data directory (often called PGDATA). Ask the server where it is:
SHOW data_directory;Reading this setting needs a superuser or membership in pg_read_all_settings. Inside the data directory, the parts that matter for table storage are:
| Path | Contents |
|---|---|
| `base/` | One subdirectory per database, named by the database's OID. Tables of the default tablespace live here. |
| `global/` | Cluster-wide catalogs such as `pg_database`. |
| `pg_tblspc/` | Symbolic links to user-defined tablespaces. |
| `pg_wal/` | Write-ahead log files, which are not table data. |
An OID (object identifier) is a number PostgreSQL assigns to each catalog object. Databases, tables, and tablespaces all get one.
Finding a table's file
Create a table and ask PostgreSQL where its data is stored:
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance numeric);
INSERT INTO accounts VALUES (1, 'alice', 100), (2, 'bob', 200);
SHOW block_size;
SELECT pg_relation_filepath('accounts');
SELECT pg_relation_size('accounts') AS bytes,
pg_relation_size('accounts') / current_setting('block_size')::int AS pages;pg_relation_filepath returns a path relative to the data directory, for example base/16384/16397. It has two parts:
16384is the OID of the current database. You can check it withSELECT oid FROM pg_database WHERE datname = current_database();.16397is the table's file node, the number used as the file name.
The block_size setting is 8192 bytes on a standard build. The last query divides the file size by that value to count the 8 KB pages the table occupies. Pages are the subject of the next chapter.
The file node is not the OID
Beginners often assume the file name equals the table's OID. It often does at first, but the two are separate values. pg_class stores the file name in the column relfilenode:
SELECT oid, relfilenode, pg_relation_filenode(oid) AS filenode
FROM pg_class
WHERE oid = 'accounts'::regclass;Some operations write a brand-new copy of a table and then swap in the new file. The table's OID stays the same, but its file node changes. Commands that do this include TRUNCATE, VACUUM FULL, CLUSTER, and ALTER TABLE forms that must rewrite every row, such as changing a column's type. You can watch it happen:
CREATE TABLE scratch (n int);
INSERT INTO scratch SELECT g FROM generate_series(1, 1000) g;
SELECT pg_relation_filepath('scratch');
TRUNCATE scratch;
SELECT pg_relation_filepath('scratch');The second path ends in a different number. The old file is removed when the transaction commits. If the transaction rolls back, the new file is discarded and the old one stays.
A few system catalogs are "mapped relations". For them pg_class.relfilenode is 0, and the real file number lives in a separate map file. Use pg_relation_filenode() or pg_relation_filepath() instead of reading relfilenode directly, because those functions handle this case.
To go the other way, from a file number found on disk back to a table, use pg_filenode_relation. Passing 0 as the tablespace means the default tablespace:
SELECT pg_filenode_relation(0, pg_relation_filenode('accounts'));Segments: files are capped at 1 GB
PostgreSQL does not keep a large table in one huge file. It splits the table into segments of at most 1 GB each. The first segment has the plain file node as its name. Later segments add a numeric suffix:
ls -l base/16384/ | grep '^.* 16397'A table of about 2.5 GB would show up as three files: 16397 and 16397.1 at 1 GB each, and 16397.2 at about 0.5 GB. A segment is always a whole number of pages, so the page layout is never cut across two files. The server finds a page by dividing its block number by the number of pages per segment. The quotient selects the file, and the remainder gives the position inside it.
The segment limit is fixed when the server is compiled. You can read it from the server:
SHOW segment_size;The default of 1 GB exists for portability, because some filesystems historically limited file size. Changing it requires building PostgreSQL from source with a different setting, and you would then have to initialize a new cluster.
Segments matter in practice for three reasons:
- A directory listing of a big database shows many files per table, so the number of files is not the number of tables.
- Backup tools that copy files must copy every segment. A missing
.1file corrupts the table. pg_relation_sizeadds the segments together and returns one total, so you rarely need to count them yourself.
Forks: several files per relation
Each table is a "relation" with more than one kind of file. These kinds are called forks. Every fork is a separate file, and each one can also be split into 1 GB segments. The fork is identified by a suffix on the file name.
| Fork | File name | Purpose |
|---|---|---|
| main | `16397` | The table's rows, stored as pages. |
| fsm | `16397_fsm` | Free space map: how much free space each page has. |
| vm | `16397_vm` | Visibility map: which pages need no cleanup and hold only rows visible to everyone. |
| init | `16397_init` | Empty template for an unlogged table, copied back after a crash. |
The main fork always exists. The free space map and visibility map are created on demand, and Chapter 10 explains what they do. The init fork exists only for unlogged tables and their indexes.
Every size function takes an optional fork name, and the default is 'main':
VACUUM accounts;
SELECT pg_relation_size('accounts', 'main') AS main_bytes,
pg_relation_size('accounts', 'fsm') AS fsm_bytes,
pg_relation_size('accounts', 'vm') AS vm_bytes;On a small, freshly vacuumed table you will typically see 8192 bytes for main and vm. The fsm value is 0 because PostgreSQL does not create a free space map for very small tables. The server finds free space in those by checking their few pages directly. Exact numbers depend on your data and on whether VACUUM has run.
Everything has its own file
A table is not the only relation with files. Each of these gets its own file node and its own forks:
- Every index. The primary key on
accountshas a separate file. - The table's TOAST table, a hidden table for large values, which a later chapter covers.
- The TOAST table's own index.
- Sequences and materialized views.
You can list them with their file paths:
SELECT c.oid::regclass AS relation,
c.relkind,
pg_relation_filepath(c.oid) AS path
FROM pg_class c
WHERE c.oid = 'accounts'::regclass
OR c.oid IN (SELECT indexrelid FROM pg_index WHERE indrelid = 'accounts'::regclass)
OR c.oid = (SELECT reltoastrelid FROM pg_class WHERE oid = 'accounts'::regclass);The relkind column shows r for an ordinary table, i for an index, and t for a TOAST table. A table with no wide columns may still have a TOAST table, though it stays empty.
Tablespaces and temporary tables
A tablespace is a directory outside the default base/ location. If you create a table in one, pg_relation_filepath returns a longer path:
CREATE TABLESPACE fast LOCATION '/mnt/ssd/pgdata';
CREATE TABLE hot_rows (id int) TABLESPACE fast;
SELECT pg_relation_filepath('hot_rows');The result looks like pg_tblspc/16400/PG_16_202307071/16384/16410. After the tablespace OID comes a directory named for the major version and the catalog version. After that come the database OID and the file node. The directory must exist and be owned by the PostgreSQL operating-system user, and creating a tablespace needs superuser rights. Skip this example if you cannot satisfy those conditions.
Temporary tables follow the same layout, but their files are named with the owning session's backend number as a prefix, such as t5_16420. They are private to the session that created them and are removed when it ends.
Common mistakes
- Assuming file name equals OID. After a rewrite they differ. Always use
pg_relation_filepath. - Editing or deleting files by hand. The server tracks these files, and removing one makes the table unreadable even if the catalog still lists it. Treat the data directory as the server's private storage.
- Copying the data directory from a running server. A plain file copy gives an inconsistent snapshot. Use
pg_basebackupor a backup tool that coordinates with the server. - Forgetting forks and segments when estimating disk use. Sum sizes with the right function instead of adding up what
lsshows for one file. - Expecting disk space back after
DELETE. Deleted rows leave space inside the file. The file usually shrinks only after a rewrite such asVACUUM FULL, a topic for later chapters.
Exercise
You run SELECT pg_relation_filepath('orders'); and get base/16384/24577. Later you run VACUUM FULL orders; and ask again. What is likely to change, and what stays the same?
Show answer
The database directory 16384 stays the same, and so does the table's OID. The file number 24577 probably changes, because VACUUM FULL writes the live rows into a new file and then swaps it in for the old one.
Exercise
A table's pg_relation_size is 3 GB. How many files does its main fork occupy with the default build, and what are they called if its file node is 30500?
Show answer
Three files: 30500 (1 GB), 30500.1 (1 GB), and 30500.2 (1 GB). The default segment size is 1 GB, and later segments get .1, .2 suffixes. If the size is slightly over 3 GB, a fourth file 30500.3 would hold the remainder.
Exercise
A colleague says a table is 8 KB because SELECT pg_relation_size('t') returned 8192, yet the disk fills up quickly. Name two things that this number leaves out.
Show answer
It leaves out the table's indexes and its TOAST table. It also leaves out the free space map and visibility map forks, because the function counts only the main fork by default. pg_total_relation_size('t') includes all of these.