5

I'm working on a project where calculations are being made for certain tables in the postgres DB, and in different parts of code, there are 2 different calculations being made:

select pg_total_relation_size ('TABLENAME'); 

and the second one:

select (relpages*8/1024) from pg_class where relname='TABLENAME' (Size in MB) 

I know that pg_total_relation_size is what I need to use, but I was wondering what does this other calculation represents, and if the second one is also some kind of size calculation, why am I getting different results for the same table?

2
  • The second one would calculate the overhead that occurs due to the fact that not every block is 100% full. The first one is the size of the data, the second one the size on disk (more or less) Commented Jul 18, 2014 at 12:38
  • 1
    Before you can ask for the right way, you need to define the target. "Table size" is pretty vague. There are a number of possible definitions as discussed in this related answer on dba.SE Commented Jul 18, 2014 at 13:25

2 Answers 2

7

You can use pg_size_pretty(pg_total_relation_side(oid)) to pretty print table size:

select nspname , relname , pg_size_pretty(pg_total_relation_size(c.oid)) as "size" from pg_class c left join pg_namespace n on n.oid = c.relnamespace where nspname not in ('pg_catalog', 'information_schema') order by pg_relation_size(c.oid) desc; 
Sign up to request clarification or add additional context in comments.

Comments

4

pg_total_relation_size - is the right way to see full table size because it includes disk space utilized by indices and TOAST data.

When you do the second-one select - you get table size only (relpages is table size in 8Kb pages). You can get TOAST and index sizes from pg_class as well but you need to do some more sql queries as described in here and sum all the sizes you've got.

2 Comments

Please link to the current version of the manual. don't fall for outdated links from Google. And the TOAST table is not the only consideration. There are more depending objects like indexes, the free space map or the visibility map. Details.
Thanks @ErwinBrandstetter - I've mentioned indexes, but didn't know about other object types. But the answer is still the same - second select is definitely underestimates table size (in common sense of the word)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.