I'm trying to get the column size for each row in a table. That's basically the combination of these two queries:
SELECT pg_size_pretty(sum(pg_column_size(COLUMN_NAME))) FROM TABLE_NAME;
And
SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'TABLE_NAME';
My first attempt was to do these two queries:
=> SELECT column_name, (SELECT pg_size_pretty(sum(pg_column_size(column_name))) FROM TABLE_NAME) FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'TABLE_NAME';
ERROR: column "columns.column_name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT column_name, (SELECT pg_size_pretty(sum(pg_column_siz...
^
=> SELECT column_name, (SELECT pg_size_pretty(sum(pg_column_size(column_name))) FROM TABLE_NAME) FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'TABLE_NAME' GROUP BY column_name;
ERROR: more than one row returned by a subquery used as an expression
Tried the following too:
SELECT column_name, (SELECT pg_size_pretty(sum(pg_column_size(column_name))) FROM TABLE_NAME) FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'TABLE_NAME' GROUP BY 1;
Which returned:
ERROR: more than one row returned by a subquery used as an expression
When I add a LIMIT 1, the result is incorrect:
SELECT column_name,
(SELECT pg_size_pretty(sum(pg_column_size(column_name))) FROM main_apirequest LIMIT 1)
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'main_apirequest'
GROUP BY 1;
It looks something like this:
column_name | pg_size_pretty
------------------+----------------
api_key_id | 11 bytes
id | 3 bytes
...
When it should be something like this (which doesn't happen because of the limit 1)
=> SELECT pg_size_pretty(sum(pg_column_size(id))) FROM main_apirequest
;
pg_size_pretty
----------------
19 MB