20

I know how to check the size of indexes and tables in Postgres (I'm using version 9.4):

SELECT
 relname AS objectname,
 relkind AS objecttype,
 reltuples AS "#entries", pg_size_pretty(relpages::bigint*8*1024) AS size
 FROM pg_class
 WHERE relpages >= 8
 ORDER BY relpages DESC;

But this doesn't show materialized views. How can I check how much disk space they are taking up?

Erwin Brandstetter
186k28 gold badges463 silver badges636 bronze badges
asked Mar 28, 2015 at 23:57

1 Answer 1

31

This is assuming that materialized views have relpages >= 8 in pg_class, which doesn't have to be the case. It can actually be empty - not populated yet, indicated by pg_class.relispopulated = FALSE. The corresponding disk file has a zero size in this case.

Try instead:

SELECT oid::regclass::text AS objectname
 , relkind AS objecttype
 , reltuples AS entries
 , pg_size_pretty(pg_table_size(oid)) AS size -- depending - see below
FROM pg_class
WHERE relkind IN ('r', 'i', 'm')
ORDER BY pg_table_size(oid) DESC;

The cast to regclass makes sure that the name of the relation is quoted and schema-qualified where needed (where the current search_path would not resolve to the same object). See:

Available values for relkind are:

r = ordinary table,
i = index,
S = sequence,
v = view,
m = materialized view,
c = composite type,
t = TOAST table,
f = foreign table

Use one of the database object size functions rather than building your own. Be aware that the "size of a table" can be defined in different ways. Details:

answered Mar 29, 2015 at 2:40
2
  • 2
    Correct answer indeed. Note that order by size is misleading as you're printing size in human-readable form making ordering sort lexicographically Commented Nov 9, 2016 at 11:23
  • @Jack: Good point. I added a more sensible ORDER BY. Commented Nov 9, 2016 at 15:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.