在Postgresql中计算列类型的大小

8
我正在尝试确定数据库中特定列的大小,例如我有两个名为sourceip、destinationip的列,它们都是16字节字段。
我认为这应该在information_schema或\d+中的某个地方,但我找不到一个特定的命令来隔离每个列类型的大小。
您可以计算数据库中列类型的大小,还是必须参考Postgresql文档中每种类型的字节大小?
1个回答

18

PostgreSQL中仅有少数类型具有固定长度,几乎所有类型都是varlena类型,即它们的长度是动态变化的。您可以检查像以下这样的查询:

 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)

如果结果不是-1,则类型长度不固定。

对于varlena类型,请使用pg_column_size函数:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接