In PostgreSQL, how do you find which tables of a database take the most disk space, and why sort by pg_total_relation_size rather than pg_relation_size?
answer
- a table is several files
- forks, TOAST and indexes
- table size plus indexes size
- sort on bytes, pretty-print last
basics
~20 sSelect pg_total_relation_size(relid) from pg_stat_user_tables, order by that bigint and wrap it in pg_size_pretty only for display. It counts the heap, its free space and visibility maps, TOAST and every index; pg_relation_size returns just the main fork.
solid answer
~40 sA PostgreSQL table is several files: the main heap fork, a free space map (`fsm`), a visibility map (`vm`), an optional TOAST table with its own index for wide values, and separate files for each index. `pg_relation_size(rel)` returns only the main fork, `pg_table_size` adds the other forks and TOAST, `pg_indexes_size` sums the indexes, and `pg_total_relation_size` is `pg_table_size + pg_indexes_size`. To rank a CMS's tables I select `relname` and `pg_total_relation_size(relid)` from `pg_stat_user_tables`, `ORDER BY` the raw `bigint`, and apply `pg_size_pretty` only in the select list, because sorting its text output puts '9 MB' above '120 GB'. `pg_database_size` gives a whole database; psql's `\dt+` shows `pg_table_size`, which leaves indexes out.
code
sql · 8 linesSELECT datname, pg_size_pretty(pg_database_size(datname)) AS size
FROM pg_database
WHERE datallowconn
ORDER BY pg_database_size(datname) DESC;
SELECT pg_size_pretty(pg_relation_size('cms.media_asset')) AS heap_only,
pg_size_pretty(pg_table_size('cms.media_asset')) AS with_toast,
pg_size_pretty(pg_total_relation_size('cms.media_asset')) AS everything;go deeper
Recall the four functions and what each adds: main fork, plus maps and TOAST, plus indexes. Sort on the bigint and use pg_size_pretty only to display it.
Explain why a table is several files: fsm and vm forks, the TOAST relation for wide values, and one relation per index. Show how the gaps between the functions locate the space.
Show the operational habits: sample sizes on a schedule to see growth, sum partitions through pg_partition_tree, and remember size queries take ACCESS SHARE and can queue behind DDL.
Frame size reporting as capacity data: which numbers you keep over time, how they feed disk and archive forecasts, and why size alone never proves bloat.
## Where a table's bytes live In PostgreSQL a table is not one file. The size functions only make sense once you know which files exist for it: - **Main fork** holds the heap, the pages that carry the rows. Files are split into 1 GB segments, so a large table spans several files. - **Free space map** (`fsm` fork) records free space per page so inserts can find room. - **Visibility map** (`vm` fork) tracks all-visible and all-frozen pages for vacuum and index-only scans. - **Init fork** exists only for unlogged relations. - **TOAST table** is a separate relation, with its own index, that stores values too wide to keep inline. A row is considered for TOAST once it exceeds about 2 kB (`TOAST_TUPLE_THRESHOLD`). A CMS that keeps article bodies or rendered HTML in `text` columns can hold most of its bytes here. - **Indexes** are relations of their own, each with its own files. ## The size functions | Function | What it counts | |---|---| | `pg_relation_size(rel)` | the main fork only, or one named fork: `'main'`, `'fsm'`, `'vm'`, `'init'` | | `pg_table_size(rel)` | all forks plus the TOAST table and its index, but no indexes | | `pg_indexes_size(rel)` | every index attached to the table | | `pg_total_relation_size(rel)` | `pg_table_size + pg_indexes_size`: the whole footprint | | `pg_database_size(name)` | every relation in one database | | `pg_size_pretty(bigint)` | formats a byte count as text with units | The relation functions take a `regclass`, so a `relid` column or a literal such as `'cms.page'::regclass` works directly, and all of them return `bigint` bytes. `pg_size_pretty` uses powers of two, so 1 kB is 1024 bytes, and `pg_size_bytes` turns such text back into bytes. ## Ranking the tables of a CMS Answer "what is big" with the total, because what fills the disk is the heap plus its TOAST data plus its indexes: ```sql SELECT schemaname, relname, pg_size_pretty(pg_total_relation_size(relid)) AS total, pg_size_pretty(pg_relation_size(relid)) AS heap, pg_size_pretty(pg_table_size(relid) - pg_relation_size(relid)) AS toast_and_maps, pg_size_pretty(pg_indexes_size(relid)) AS indexes FROM pg_stat_user_tables ORDER BY pg_total_relation_size(relid) DESC LIMIT 10; ``` Read the split column by column: 1. If `toast_and_maps` dwarfs `heap`, wide values in TOAST carry the table, which is typical for `cms.page_revision` storing every saved body. 2. If `indexes` rivals the heap, review which indexes earn their space. Usage counters for each index live in `pg_stat_user_indexes`, which the index-upkeep leaf covers. 3. Record the numbers on a schedule. One reading says what is big; two readings a week apart say what is growing. ## Pitfalls - **Sorting the pretty text.** `pg_size_pretty` returns `text`, so `ORDER BY` on it sorts alphabetically and '9 MB' lands above '120 GB'. Sort on the `bigint`. - **Partitioned tables.** A partitioned parent holds no rows of its own, so the functions report zero bytes for it. Sum the partitions, for example `sum(pg_total_relation_size(relid))` over `pg_partition_tree('cms.page_view')`. - **`pg_class.relpages` is an estimate.** It is refreshed only by `VACUUM`, `ANALYZE` and a few DDL commands, while the size functions stat the real files. - **Locks.** The functions open the table and each of its indexes with `ACCESS SHARE`, so on a busy table they wait in the lock queue behind a pending `ACCESS EXCLUSIVE` request such as an `ALTER TABLE`. - **Permissions.** `pg_database_size` needs `CONNECT` on that database, granted by default, or the privileges of `pg_read_all_stats`. - **psql shortcuts.** The Size column of `\dt+` is `pg_table_size` (no indexes), `\di+` shows each index, and `\l+` shows `pg_database_size`. ## Tracking growth A single ranking answers "what is big today". The more useful operational question is "what is growing, and how fast", and PostgreSQL keeps no size history for you. A minimal habit: - **Sample on a schedule.** Insert `now()`, `relid`, `relname` and `pg_total_relation_size(relid)` from `pg_stat_user_tables` into a history table once a day. - **Compute deltas.** Subtract consecutive samples per table; a table that grows by a constant amount each day is behaving like an append log, while sudden jumps after deploys point at a new feature or a new index. - **Watch the split, not just the total.** Growth in TOAST while the heap stays flat means wider values, such as larger rendered pages; growth in indexes alone means someone added one. - **Add the whole database.** `pg_database_size(current_database())` in the same row lets you check that the tables you rank explain most of the growth. The sizes these functions report are file sizes on disk, so they also include space that `VACUUM` has marked free inside the files but not returned to the operating system. ## What a size does not tell you A size is not a health verdict. Half of a heap can be dead tuples or reusable free space; measuring that is bloat measurement, which belongs to the vacuum-bloat leaf. WAL in `pg_wal` is not part of any database's size either, so a full disk can have causes these functions never show.
- How do you measure the size of a partitioned table in PostgreSQL?The partitioned parent stores no rows, so `pg_total_relation_size` on it reports zero. Sum over the partitions instead: `SELECT pg_size_pretty(sum(pg_total_relation_size(relid))) FROM pg_partition_tree('cms.page_view');`. `pg_partition_tree` returns every partition at every level, including the parent, which contributes nothing.
- Why can pg_table_size be several times pg_relation_size for a CMS revisions table?`pg_relation_size` counts only the main heap fork. Article bodies and rendered HTML are wide `text` values, and once a row passes about 2 kB PostgreSQL compresses them and moves them out of line into the table's TOAST relation. `pg_table_size` adds that TOAST table and its index plus the free space and visibility maps, so most of the bytes can sit outside the heap.
- Can a size query get stuck on a busy production table?Yes. The size functions open the table and its indexes with `ACCESS SHARE`. That lock conflicts only with `ACCESS EXCLUSIVE`, but a request queued behind a waiting `ALTER TABLE` waits too, so a monitoring query can hang until the DDL finishes or its `lock_timeout` fires.
- pg_relation_size gives a table's full footprint, indexes and TOAST included.
- Ordering by the pg_size_pretty output ranks tables from largest to smallest.
- pg_class.relpages always reflects the table's current size on disk.
- pg_total_relation_size on a partitioned parent returns the size of all its partitions.
- pg_database_size includes the WAL files stored in pg_wal.