如何在PostgreSQL中列出索引的成员及对应属性?
PostgreSQL 索引成员列表查询方法
直接用PostgreSQL的系统表和内置函数就能获取你要的索引成员信息,执行以下SQL查询即可:
SELECT c.relname AS table_name, idx.relname AS index_name, indisunique AS is_unique, idxkey.ordinality AS ordinal, pg_get_expr(idxkey.indexkey, c.oid) AS member, idxopt.option = 0 AS is_ascending FROM pg_index i JOIN pg_class idx ON i.indexrelid = idx.oid JOIN pg_class c ON i.indrelid = c.oid JOIN pg_namespace n ON c.relnamespace = n.oid LEFT JOIN LATERAL unnest(i.indkey) WITH ORDINALITY idxkey(indexkey) ON true LEFT JOIN LATERAL unnest(i.indoption) WITH ORDINALITY idxopt(option) ON idxkey.ordinality = idxopt.ordinality WHERE n.nspname = 'public' -- 替换为你的schema名称 AND c.relname = 'employee'; -- 替换为目标表名
关键逻辑说明
pg_index:存储索引核心属性,比如是否唯一、索引字段编号、排序规则等pg_class:关联表和索引的元数据,用来获取表名和索引名unnest(i.indkey) WITH ORDINALITY:展开索引包含的字段编号,同时获取字段在索引中的顺序(ordinal)pg_get_expr:把字段编号转换成对应的字段名或计算表达式(比如salary + bonus)idxopt.option:判断排序方向,0对应升序(true),1对应降序(false)
执行后会得到你需要的格式结果:
| table_name | index_name | is_unique | ordinal | member | is_ascending |
|---|---|---|---|---|---|
| employee | idx_employee_1 | true | 1 | name | true |
| employee | idx_employee_2 | false | 1 | (salary + bonus) | false |
| employee | idx_employee_2 | false | 2 | name | true |
如果要查询所有表的索引,去掉AND c.relname = 'employee'条件即可。
内容的提问来源于stack exchange,提问作者Joe DiNottra
相关产品推荐
相关产品推荐

