PostgreSQL provides a series of functions to determine the space occupied by various parts.
Function
Statistical Scope
pg_total_relation_size(oid)
Entire relation, including table, indexes, TOAST, etc.
pg_indexes_size(oid)
Space occupied by relation’s index portion
pg_table_size(oid)
Space occupied by relation excluding indexes
pg_relation_size(oid)
Get size of a relation’s main file part (main fork)
pg_relation_size(oid, 'main')
Get relation’s main fork size
pg_relation_size(oid, 'fsm')
Get relation’s fsm fork size
pg_relation_size(oid, 'vm')
Get relation’s vm fork size
pg_relation_size(oid, 'init')
Get relation’s init fork size
Although physically a table consists of so many files, logically we usually only care about the size of two things: table and indexes. Therefore, the main functions used here are pg_indexes_size and pg_table_size, whose sum equals pg_total_relation_size for regular tables.
The table size portion can typically be calculated as:
Note that TOAST tables also have their own indexes, but there is only one, so using pg_total_relation_size(reltoastrelid) can calculate the overall size of the TOAST table.
Example: Statistics for a Specific Table and Related Relations UDTF
SELECToid,relname,relnamespace::RegNamespace::Textasnspname,relkindasrelkind,reltuplesastuples,relpagesaspages,pg_total_relation_size(oid)assizeFROMpg_classWHEREoid=ANY(array(SELECT16418asid-- main
UNIONALLSELECTindexrelidFROMpg_indexWHEREindrelid=16418-- index
UNIONALLSELECTreltoastrelidFROMpg_classWHEREoid=16418));-- toast
This can be wrapped as a UDTF: pg_table_size_detail, for convenient use:
CREATEORREPLACEFUNCTIONpg_table_size_detail(relationRegClass)RETURNSTABLE(idoid,pidoid,relnamename,nspnametext,relkind"char",tuplesbigint,pagesinteger,sizebigint)AS$$BEGINRETURNQUERYSELECTrel.oid,relation::oid,rel.relname,rel.relnamespace::RegNamespace::Textasnspname,rel.relkindasrelkind,rel.reltuples::bigintastuples,rel.relpagesaspages,pg_total_relation_size(oid)assizeFROMpg_classrelWHEREoid=ANY(array(SELECTrelationasid-- main
UNIONALLSELECTindexrelidFROMpg_indexWHEREindrelid=relation-- index
UNIONALLSELECTreltoastrelidFROMpg_classWHEREoid=relation));-- toast
END;$$LANGUAGEPlPgSQL;SELECT*FROMpg_table_size_detail(16418);