Calculating the size of a column type in Postgresql

前端 未结 1 338
萌比男神i
萌比男神i 2021-01-12 21:00

I am trying to figure out how to determine the size of a specific column in database for instance I have two columns called sourceip, destinationip that are both 16 byte fie

1条回答
  •  [愿得一人]
    2021-01-12 21:19

    only few types in pg has fixed length - almost all types are varlena type - it has dynamic length. You can check queries like

     postgres=# select typlen from pg_type where oid = 'int'::regtype::oid;
      typlen 
     --------
           4
     (1 row)
    
    
     postgres=# select attlen from pg_attribute where attrelid = 'x'::regclass and attname = 'a';
      attlen 
     --------
           4
     (1 row)
    

    When result is not -1, then type has not fixed length

    for varlena types use pg_column_size function:

    postgres=# \df *size*
                                       List of functions
       Schema   |          Name          | Result data type | Argument data types |  Type  
    ------------+------------------------+------------------+---------------------+--------
     pg_catalog | pg_column_size         | integer          | "any"               | normal
     pg_catalog | pg_database_size       | bigint           | name                | normal
     pg_catalog | pg_database_size       | bigint           | oid                 | normal
     pg_catalog | pg_indexes_size        | bigint           | regclass            | normal
     pg_catalog | pg_relation_size       | bigint           | regclass            | normal
     pg_catalog | pg_relation_size       | bigint           | regclass, text      | normal
     pg_catalog | pg_size_pretty         | text             | bigint              | normal
     pg_catalog | pg_size_pretty         | text             | numeric             | normal
     pg_catalog | pg_table_size          | bigint           | regclass            | normal
     pg_catalog | pg_tablespace_size     | bigint           | name                | normal
     pg_catalog | pg_tablespace_size     | bigint           | oid                 | normal
     pg_catalog | pg_total_relation_size | bigint           | regclass            | normal
    (12 rows)
    
    
    
     postgres=# select pg_column_size('Hello');
      pg_column_size 
     ----------------
              6
     (1 row)
    
     postgres=# select pg_column_size(10);
      pg_column_size 
     ----------------
                   4
     (1 row)
    
     postgres=# select pg_column_size(now());
      pg_column_size 
     ----------------
                   8
    

    0 讨论(0)
提交回复
热议问题