Skip to content

Instantly share code, notes, and snippets.

@gc
Last active July 15, 2022 12:51
Show Gist options
  • Save gc/bc1619f135b9a23ed63fad0349dc3a7e to your computer and use it in GitHub Desktop.
Save gc/bc1619f135b9a23ed63fad0349dc3a7e to your computer and use it in GitHub Desktop.

Shows the size of every postgres database column:

CREATE FUNCTION tc_column_size(table_name text, column_name text)
    RETURNS BIGINT AS
$$
    declare response BIGINT;
BEGIN
    EXECUTE 'select sum(pg_column_size(t."' || column_name || '")) from "' || table_name || '" t ' into response;
    return response;
END;
$$
    LANGUAGE plpgsql;

SELECT
    z.table_name,
    z.column_name,
    pg_size_pretty(z.size)
FROM (
    SELECT
        table_name,
        column_name,
        tc_column_size(table_name, column_name) size
    FROM
        information_schema.columns
    WHERE
        table_schema = 'public') AS z
WHERE
    size IS NOT NULL
    -- and z.table_name = 'my_table' -- <--- uncomment to filter a table
ORDER BY
    z.size DESC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment