PostgreSQL: Prepare SQL statement for determining the size of the partitions of a table

14 Views Asked by At

To know the size of the partitions of a table I use the following anonymous block.

DO $$ 
DECLARE 
  query text; 
  table_size bigint; 
BEGIN
  FOR i IN 1..4 LOOP
    query = 'SELECT pg_total_relation_size(''ShipsSpacePart_' ||
      i || ''') INTO table_size;';
    RAISE INFO 'Query: "%"', query;
    PERFORM query; 
    RAISE INFO '%: %', i, table_size;
  END LOOP;
END;$$;

However, I don't get the results expected

ais=# DO $$
ais$# DECLARE
ais$#   query text;
ais$#   table_size bigint;
ais$# BEGIN
ais$#   FOR i IN 1..4 LOOP
ais$#     query = 'SELECT pg_total_relation_size(''ShipsSpacePart_' ||
ais$#       i || ''') INTO table_size;';
ais$#     RAISE INFO 'Query: "%"', query;
ais$#     PERFORM query;
ais$#     RAISE INFO '%: %', i, table_size;
ais$#   END LOOP;
ais$# END;$$;
INFO:  Query: "SELECT pg_total_relation_size('ShipsSpacePart_1') INTO table_size;"
INFO:  1: <NULL>
INFO:  Query: "SELECT pg_total_relation_size('ShipsSpacePart_2') INTO table_size;"
INFO:  2: <NULL>
INFO:  Query: "SELECT pg_total_relation_size('ShipsSpacePart_3') INTO table_size;"
INFO:  3: <NULL>
INFO:  Query: "SELECT pg_total_relation_size('ShipsSpacePart_4') INTO table_size;"
INFO:  4: <NULL>
DO

However I can obtain manually the size of the partitions

ais=# DO $$
ais$# DECLARE
ais$#   query text;
ais$#   table_size bigint;
ais$# BEGIN
ais$#   SELECT pg_total_relation_size('ShipsSpacePart_1') INTO table_size;
ais$#   RAISE INFO '1: %', table_size;
ais$#   SELECT pg_total_relation_size('ShipsSpacePart_2') INTO table_size;
ais$#   RAISE INFO '2: %', table_size;
ais$#   SELECT pg_total_relation_size('ShipsSpacePart_3') INTO table_size;
ais$#   RAISE INFO '3: %', table_size;
ais$#   SELECT pg_total_relation_size('ShipsSpacePart_4') INTO table_size;
ais$#   RAISE INFO '4: %', table_size;
ais$# END;$$;
INFO:  1: 54444032
INFO:  2: 95830016
INFO:  3: 102146048
INFO:  4: 55836672
DO

Any idea about what I am doing wrong ?

Esteban

0

There are 0 best solutions below