我需要能够查询 PostgreSQL 数据库以获取有关现有索引及其详细信息的信息。
在 SQL Server 上,我可以执行以下操作来获取所有索引的所有表/索引/列的列表:
select TABLE_NAME, INDEX_NAME, NON_UNIQUE, COLUMN_NAME
from INFORMATION_SCHEMA.STATISTICS
where TABLE_SCHEMA = 'my_schema'
order by TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX
看来INFORMATION_SCHEMA的STATISTICS表是一个SQL Server扩展。我怎样才能在 PostgreSQL 中做同样的事情?
编辑:我专门尝试返回非规范化结果集,如下所示
TableName, IndexName, UniqueFl, ColumnName
因此,我为所有索引中的每一列返回一行。
谢谢, 乔恩
您在寻找什么元数据?
如果您知道自己在寻找什么,那么您可以找到各种各样的精彩内容。例如,这是索引统计信息和元数据的转储。
SELECT *, pg_size_pretty(pg_relation_size(indexrelname::text))
FROM pg_stat_all_indexes
WHERE schemaname = 'public'
挖掘 postgresql wiki 会发现各种好东西。
我用来查看索引列表及其实际大小的查询:
SELECT relname AS name,
reltuples as count, (c.relpages * (8192 /1024) / 1024 ) as size_mb,
c.relfilenode::regclass, cast(c.oid::regclass as TEXT), c.relnatts, c.relkind
FROM pg_class c, pg_namespace n
WHERE
n.nspname ='MyNamespace'
and n.oid = c.relnamespace
and c.relkind = 'i'
ORDER BY c.relpages DESC;
PostgreSQL不提供“INFORMATION_SCHEMA.STATISTICS”视图。 但我们可以像这样查询一些元数据:
select
t.relname as table_name,
i.relname as index_name,
m.amname as index_type,
case ix.indisunique when 'f' then 'NO' else 'YES' end UNIQUENESS,
case ix.indisprimary when 'f' then 'NO' else 'YES' end IS_PRIMARY,
case ix.indisclustered when 'f' then 'NO' else 'YES' end IS_CLUSTERED,
case ix.indisvalid when 'f' then 'NO' else 'YES' end IS_VALID,
a.attname as column_name
from pg_namespace n,
pg_am m,
pg_class t,
pg_class i,
pg_index ix,
pg_attribute a
where n.oid=t.relnamespace
and m.oid=i.relam
and t.oid = ix.indrelid
and i.oid = ix.indexrelid
and a.attrelid = t.oid
and a.attnum = ANY(ix.indkey)
and n.nspname=?
and t.relkind = 'r'
and t.relname=?
and i.relname not in (select conname from pg_constraint)
order by t.relname, i.relname, a.attnum;
由于主键/唯一键/检查/排除约束可能会默认生成索引,所以我们应该过滤系统生成的索引。
在整个目录中,我唯一能找到可以按索引顺序读取索引列的位置是在pg_index.indkey
列中。问题出在法
http://www.postgresql.org/docs/current/static/information-schema.html http://www.postgresql.org/docs/current/static/monitoring-stats.html