List columns with indexes in PostgreSQL

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

    Here's a function that wraps cope360's answer:

    CREATE OR REPLACE FUNCTION getIndices(_table_name varchar)
      RETURNS TABLE(table_name varchar, index_name varchar, column_name varchar) AS $$
      BEGIN
        RETURN QUERY
        select
        t.relname::varchar as table_name,
        i.relname::varchar as index_name,
        a.attname::varchar as column_name
    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 = _table_name
    order by
        t.relname,
        i.relname;
      END;
      $$ LANGUAGE plpgsql;
    

    Usage:

    select * from getIndices('')
    

提交回复
热议问题