You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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_nameindex_nameis_uniqueordinalmemberis_ascending
employeeidx_employee_1true1nametrue
employeeidx_employee_2false1(salary + bonus)false
employeeidx_employee_2false2nametrue

如果要查询所有表的索引,去掉AND c.relname = 'employee'条件即可。

内容的提问来源于stack exchange,提问作者Joe DiNottra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:34:55