What's the difference between pg_table_size()
, pg_relation_size()
& pg_total_relation_size()
?
I understand the basic differences explained in the documentation, but what does it imply in terms of how much space my table is actually using?
What's the difference between pg_table_size()
, pg_relation_size()
& pg_total_relation_size()
?
I understand the basic differences explained in the documentation, but what does it imply in terms of how much space my table is actually using?
For a random table:
# select
pg_relation_size(20306, 'main') as main,
pg_relation_size(20306, 'fsm') as fsm,
pg_relation_size(20306, 'vm') as vm,
pg_relation_size(20306, 'init') as init,
pg_table_size(20306),
pg_indexes_size(20306) as indexes,
pg_total_relation_size(20306) as total;
main | fsm | vm | init | pg_table_size | indexes | total
--------+-------+------+------+---------------+---------+--------
253952 | 24576 | 8192 | 0 | 286720 | 196608 | 483328
(1 row)
From that, you can tell pg_table_size
is the sum of all the return values of pg_relation_size
. And pg_total_relation_size
is the sum of pg_table_size
and pg_indexes_size
.
If you want to know how much space your tables are using, use pg_table_size
and pg_total_relation_size
to think about them -- one number is table-only, and one number is table + indexes.
Check the storage file layout for some info about what fsm
, vm
, and init
mean, and how they're stored on disk.
I am pretty sure after looking into the below image you will get a good understanding of various size relationships. I have made this diagram after reading all the answers mentioned in this answer section & analyzing more in DB for the query.
For storage file layout fsm, vm, and init mean, you can get from this link like @jmelesky mentioned.
pg_table_size
: Disk space used by the specified table, excluding indexes (but including TOAST, free space map, and visibility map)
pg_relation_size
: The size of the main data fork of the relation
select
pg_size_pretty(pg_total_relation_size(relid)) as total_size,
pg_size_pretty(pg_relation_size(relid, 'main')) as relation_size_main,
pg_size_pretty(pg_relation_size(relid, 'fsm')) as relation_size_fsm,
pg_size_pretty(pg_relation_size(relid, 'vm')) as relation_size_vm,
pg_size_pretty(pg_relation_size(relid, 'init')) as relation_size_init,
pg_size_pretty(pg_table_size(relid)) as table_size,
pg_size_pretty(pg_total_relation_size(relid) - pg_relation_size(relid)) as external_size
from
pg_catalog.pg_statio_user_tables
where
schemaname = 'XXXX'
and relname like 'XXXXXX';
total_size | 6946 MB
relation_size_main | 953 MB
relation_size_fsm | 256 kB
relation_size_vm | 32 kB
relation_size_init | 0 bytes
table_size | 6701 MB
external_size | 5994 MB
so pg_table_size is not only the sum of all the return values of pg_relation_size but you have to add toast size
toast_bytes | 5748 MB