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