Pergunta

I'm trying to understand 1) what components make a postgres database, and 2) how to determine the total size of each type, i.e., 40 MB Tables, 30 MB Indices, etc..

I am running version 9.2.

Best I understand it, the following queries should give me the total sizes of the database, all tables, and all indices.

Database: select pg_size_pretty(pg_database_size('postgres'))
Output: 5272 kB

Tables: select pg_size_pretty(SUM(pg_table_size(relid))) FROM pg_stat_all_tables Output: 3720 kB

Indices: select pg_size_pretty(SUM(pg_indexes_size(relid))) FROM pg_stat_all_tables Output: 2712 kB

The obvious problem is that the Tables and Indices add up to more than the Database itself. So, either my queries are wrong, or I'm not understanding how sizes are represented.

Can someone please tell me what is wrong with my queries? Also, are there other major components that I am overlooking?

Foi útil?

Solução

The error stems from counting TOAST tables twice. Per documentation:

pg_table_size(regclass) ... Disk space used by the specified table, excluding indexes (but including TOAST, free space map, and visibility map)

Bold emphasis mine. But pg_stat_all_tables lists TOAST tables, too. Thereby you count that space twice.
Plus, you have to exclude object from the information_schema, which are views. You would count repeatedly again.

Try these queries, they add up for me. tests in Postgres 9.3:

SELECT pg_size_pretty(pg_database_size('postgres')) -- 6306 kB

Using pg_stat_all_tables:

SELECT count(*), pg_size_pretty(SUM(pg_table_size(relid)))
FROM   pg_stat_all_tables
WHERE  schemaname NOT IN ('information_schema', 'pg_toast'); -- 3848 kB

SELECT count(*), pg_size_pretty(SUM(pg_indexes_size(relid)))
FROM   pg_stat_all_tables
WHERE  schemaname NOT IN ('information_schema', 'pg_toast'); -- 2456 kB

Compare to data from pg_class (that's the base table and should be the reference):

SELECT count(*), pg_size_pretty(SUM(pg_total_relation_size(c.oid)))
FROM   pg_class c
JOIN   pg_namespace n ON n.oid = c.relnamespace
WHERE  relkind = 'r'
AND    n.nspname <> 'information_schema'  -- 6304 kB
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top