检查postgres中的多个表大小

时间:2015-04-07 02:09:30

标签: sql postgresql

我找到了关于如何检查Postgres中表格大小的查询

select pg_size_pretty(pg_relation_size('the_table'));

我想从多个表中获取大小。 我的数据库有这种表名:

tblresource_01012014
tblresource_02012014
tblresource_03012014
...

它的名字有日期。我想获得特定月份的大小。像,

select pg_size_pretty(pg_relation_size('tblresource_**012014'));

这个查询绝对错了。任何人都知道什么是正确的查询来执行

我的解决方案
嘿伙计们,现在我有一个解决方案,这很简单,但我不会说这是一个很好的答案,因为它可能只适用于我的情况。并没有完全达到我的目标。我在这里怎么做。

select table_name, pg_size_pretty(pg_relation_size(table_name))
from information_schema.tables
where table_name like 'tblresource_%012014'

2 个答案:

答案 0 :(得分:1)

您可以使用查询生成值:

select pg_size_pretty(pg_relation_size('tblresource_' || lpad(n.n::varchar, 2, '0') || '012014'))
from generate_series(1, 12) n(n)

答案 1 :(得分:0)

SELECT tbl tbl_name
    ,pg_size_pretty(pg_relation_size(format('%s', t.tbl))) size
FROM (
    SELECT table_name tbl
    FROM information_schema.tables
    WHERE table_schema = 'public'
        AND table_type = 'BASE TABLE'
        AND table_name ilike '%tblresource_%' --your table
        AND table_name ilike '%012014' --to search 
    ) t;

sqlfiddle demo


你可以将上面的select包装成如下所示的函数

CREATE OR REPLACE FUNCTION get_tblresource_size (_yr TEXT)
RETURNS TABLE (
        tbl_name TEXT
        ,size TEXT
        ) AS $$

BEGIN
    RETURN QUERY

    SELECT tbl::TEXT tbl_name
        ,pg_size_pretty(pg_relation_size(format('%s', t.tbl))) size
    FROM (
        SELECT table_name tbl
        FROM information_schema.tables
        WHERE table_schema = 'public'
            AND table_type = 'BASE TABLE'
            AND table_name ilike '%tblresource_%'
            AND table_name ilike '%' || _yr || '' --012014 will come here
        ) t;
END $$

LANGUAGE plpgsql

函数调用:

select * from get_tblresource_size('012014') --passing the search value