Size Breakdown Heap Index And Toast

Split a table footprint with pg_table_size, pg_indexes_size, pg_total_relation_size, and per-fork pg_relation_size to see where bytes really go.

SqlResilience

Code

snippet
-- 一张表的磁盘占用 = 堆(main) + 行外 TOAST + 索引
-- pg_table_size 含堆与 TOAST,pg_indexes_size 只算索引,total 是两者之和
CREATE TABLE docs (id integer PRIMARY KEY, body text);

-- 500 行 × ~5KB 高熵文本(md5 随机串拼接,几乎不可压缩),
-- 稳定越过 2KB 行外阈值,确保 TOAST fork 真实产生字节
INSERT INTO docs
SELECT g, (SELECT string_agg(md5(random()::text), '')
           FROM generate_series(1, 155))
FROM generate_series(1, 500) g;
CREATE INDEX docs_body_idx ON docs (lower(left(body, 20)));

SELECT
    pg_size_pretty(pg_table_size('docs'))          AS heap_and_toast,
    pg_size_pretty(pg_indexes_size('docs'))        AS all_indexes,
    pg_size_pretty(pg_total_relation_size('docs')) AS grand_total;

-- 大字段被 TOAST 出行外:堆里只剩 18 字节指针,TOAST fork 占大头
-- 按 fork 细分可以逐块核对:main 应接近 500 × (行头 + 指针),
-- toast 接近分块总量(高熵文本 pglz 收益不足默认放弃压缩,出行外但未压缩),
-- init 是首次 vacuum 前的空 fork
SELECT
    relfork,
    pg_size_pretty(pg_relation_size('docs', relfork)) AS bytes
FROM (VALUES ('main'::text), ('toast'), ('init')) AS forks(relfork)
ORDER BY pg_relation_size('docs', relfork) DESC;

The size identity

pg_table_size covers heap plus TOAST, pg_indexes_size covers all indexes, and pg_total_relation_size is their sum — the demo prints the three in pg_size_pretty form for a 500-row table.

Making TOAST real

Each row carries ~5KB of high-entropy text (155 md5(random()::text) values concatenated), which crosses the out-of-line threshold and cannot compress back inline — so the toast fork genuinely holds bytes. The fork breakdown queries pg_relation_size per fork and sorts descending.

Expected shape of the forks

main stays near 500 × (row header + pointer) because the payload moved out; toast carries the chunk total — for this high-entropy payload pglz falls short of its default compression bar and stores the value uncompressed, so the fork holds the raw chunked bytes; init is empty until the first vacuum. The comments state these as expected shapes — actual byte counts depend on version and chunking.

Interactive Tools for This Topic

FAQ

Why does the demo use incompressible text?
Compressible text would stay inline under the 2KB threshold, leaving the toast fork near zero and falsifying the breakdown the snippet demonstrates.
What relationship holds between the three size functions?
pg_total_relation_size equals pg_table_size (heap + toast) plus pg_indexes_size — the identity the first query prints.