List columns with indexes in PostgreSQL

后端 未结 23 2022
我在风中等你
我在风中等你 2020-11-27 09:14

I would like to get the columns that an index is on in PostgreSQL.

In MySQL you can use SHOW INDEXES FOR table and look at the Column_name

23条回答
  •  孤街浪徒
    2020-11-27 09:47

    The accepted answer by @cope360 is good, but I wanted something a little more like Oracle's DBA_IND_COLUMNS, ALL_IND_COLUMNS, and USER_IND_COLUMNS (e.g., reports the table/index schema and the position of the index in a multicolumn index), so I adapted the accepted answer into this:

    with
     ind_cols as (
    select
        n.nspname as schema_name,
        t.relname as table_name,
        i.relname as index_name,
        a.attname as column_name,
        1 + array_position(ix.indkey, a.attnum) as column_position
    from
         pg_catalog.pg_class t
    join pg_catalog.pg_attribute a on t.oid    =      a.attrelid 
    join pg_catalog.pg_index ix    on t.oid    =     ix.indrelid
    join pg_catalog.pg_class i     on a.attnum = any(ix.indkey)
                                  and i.oid    =     ix.indexrelid
    join pg_catalog.pg_namespace n on n.oid    =      t.relnamespace
    where t.relkind = 'r'
    order by
        t.relname,
        i.relname,
        array_position(ix.indkey, a.attnum)
    )
    select * 
    from ind_cols
    where schema_name = 'test'
      and table_name  = 'indextest'
    order by schema_name, table_name
    ;
    

    This gives an output like:

     schema_name | table_name | index_name | column_name | column_position 
    -------------+------------+------------+-------------+-----------------
     test        | indextest  | testind1   | singleindex |               1
     test        | indextest  | testind2   | firstoftwo  |               1
     test        | indextest  | testind2   | secondoftwo |               2
    (3 rows)
    

提交回复
热议问题