【问题标题】:Is there a easy way to find number of index of a table?有没有一种简单的方法来查找表的索引数?
【发布时间】:2013-11-16 23:01:33
【问题描述】:

我有一个名为 User 的表,它有列 uid、age 等。 首先我运行 \d+ User; 然后我可以看到它告诉我以下信息:

Indexes:
    "users_pkey" PRIMARY KEY, btree (uid)

所以我知道 uid 被用作索引。 然后我用

SELECT COUNT(uid) FROM User;

获取索引的数量。

但是有没有更好的办法,比如我可以用pg_class,pg_stats ...

【问题讨论】:

标签: sql postgresql count indexing


【解决方案1】:

您可以从目录中获取一个表的索引数量:

SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, i.indisvalid, pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),
  pg_catalog.pg_get_constraintdef(con.oid, true), contype, condeferrable, condeferred, c2.reltablespace
FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i
  LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('p','u','x'))
WHERE c.oid = 'tablename'::regclass AND c.oid = i.indrelid AND i.indexrelid = c2.oid
ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname;

只需将选择部分替换为适当的计数语句即可获得数字。

(注意:要让 psql 显示这种查询,请以psql -E 运行。)

【讨论】:

    【解决方案2】:

    首先,user is a reserved word。永远不要将其用作标识符。

    “索引数”可能是指“行数”。

    用于计算表中的所有行,index is only going to be useful, if it is considerably smaller than the table itself(在 Postgres 9.2 中使用仅索引扫描)。

    您的查询:

    SELECT COUNT(uid) FROM tbl;
    

    实际上计算了在表tbl 中可以找到多少uid 的非空值——这恰好与没有NULL 值的列的(活动)行总数一致。如果您真的想计算行数,请改用:

    SELECT COUNT(*) FROM tbl;
    

    略短且更快。

    如果基于上次 ANALYZE 运行的估计足够好,您可以查询系统目录:

    SELECT reltuples FROM pg_class WHERE oid = 'my_schema.my_tbl'::regclass;
    

    显然要快得多,因为只需读取一行。 请参阅Postgres Wiki about counting 了解行数统计方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 2020-10-18
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多