Skip to content

Instantly share code, notes, and snippets.

@jakeonrails
Created October 15, 2012 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakeonrails/3895690 to your computer and use it in GitHub Desktop.
Save jakeonrails/3895690 to your computer and use it in GitHub Desktop.
Postgres table and index sizes
SELECT CASE WHEN total IS NULL THEN '' ELSE name END AS table,
index,
pg_size_pretty(size) AS size,
CASE WHEN total IS NULL THEN '' ELSE pg_size_pretty(total) END AS total
FROM
(SELECT name,
index,
size,
total
FROM
(SELECT c.relname AS name, '' as index,
pg_relation_size(c.relname::text) AS Size,
pg_total_relation_size(c.relname::text) AS total
FROM pg_class c
LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','')
AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_table_is_visible(c.oid)
UNION
SELECT c3.relname AS name,
c2.relname AS index,
pg_relation_size(c2.relname::text) AS size,
NULL AS total
FROM pg_class c2
LEFT JOIN pg_index i ON c2.oid = i.indexrelid
LEFT JOIN pg_class c1 ON c1.oid = i.indrelid
RIGHT OUTER JOIN pg_class c3 ON c3.oid = c1.oid
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c3.relnamespace
WHERE c3.relkind IN ('r','')
AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(c3.oid)
) tmp1
WHERE index IS NOT NULL
ORDER BY name, index
) tmp2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment