List columns with indexes in PostgreSQL

后端 未结 23 2009
我在风中等你
我在风中等你 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条回答
  •  猫巷女王i
    2020-11-27 09:58

    If you want to preserve column order in the index, here's a (very ugly) way to do that:

    select table_name,
        index_name,
        array_agg(column_name)
    from (
        select
            t.relname as table_name,
            i.relname as index_name,
            a.attname as column_name,
            unnest(ix.indkey) as unn,
            a.attnum
        from
            pg_class t,
            pg_class i,
            pg_index ix,
            pg_attribute a
        where
            t.oid = ix.indrelid
            and i.oid = ix.indexrelid
            and a.attrelid = t.oid
            and a.attnum = ANY(ix.indkey)
            and t.relkind = 'r'
            and t.relnamespace = 
        order by
            t.relname,
            i.relname,
            generate_subscripts(ix.indkey,1)) sb
    where unn = attnum
    group by table_name, index_name
    

    column order is stored in the pg_index.indkey column, so I ordered by the subscripts from that array.

提交回复
热议问题