List columns with indexes in PostgreSQL

后端 未结 23 1961
我在风中等你
我在风中等你 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:53

    When playing around with indexes the order of which columns are constructed in the index is as important as the columns themselves.

    The following query lists all indexes for a given table and all their columns in a sorted fashion.

    SELECT
      table_name,
      index_name,
      string_agg(column_name, ',')
    FROM (
           SELECT
             t.relname AS table_name,
             i.relname AS index_name,
             a.attname AS column_name,
             (SELECT i
              FROM (SELECT
                      *,
                      row_number()
                      OVER () i
                    FROM unnest(indkey) WITH ORDINALITY AS a(v)) a
              WHERE v = 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.relname LIKE 'tablename'
           ORDER BY table_name, index_name, i
         ) raw
    GROUP BY table_name, index_name
    

提交回复
热议问题