I would like to run the following query on my database:
SELECT nspname || '.' || relname AS relation,
pg_size_pretty(pg_total_relation_size(C.oid)) AS total_size_pretty, pg_total_relation_size(C.oid) AS total_size
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname NOT IN ('pg_catalog', 'information_schema')
AND C.relkind <> 'i'
AND nspname !~ '^pg_toast'
Then for each row in the result run:
SELECT pg_size_pretty(dead_tuple_len + free_space) AS recoverable_space_pretty, (dead_tuple_len + free_space) AS recoverable_space FROM extensions.pgstattuple(relation);
How can I do that in Postgresql returning a result combining the two so I for each row get: relation, total_size_pretty, total_size, recoverable_space_pretty, recoverable_space?
BONUS: I would also like to output the result as CSV
CTEwith aCOPYstatement should suffice. I can post a generic solutionrelationfrom each row in first query within theFROM extensions.pgstattuple(relation). So in other words, for each row I will query two more columns based onrelationCOPY ( WITH j AS ( SELECT nspname || '.' || relname AS relation, pg_size_pretty(pg_total_relation_size(C.oid)) AS total_size_pretty, pg_total_relation_size(C.oid) AS total_size FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) WHERE nspname NOT IN ('pg_catalog', 'information_schema') AND C.relkind <> 'i' AND nspname !~ '^pg_toast') SELECT extensions.pgstattuple(j.relation) FROM j ) TO STDOUT CSV HEADER;Hopefully something we can work on :DCOPY ( WITH j AS ( SELECT 1 AS q1 ) SELECT j.q1+1 AS q2 FROM j) TO STDOUT CSV HEADER;ERROR: "pg_buffercache" (view) is not supported