List columns with indexes in PostgreSQL

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

    Some sample data...

    create table test (a int, b int, c int, constraint pk_test primary key(a, b));
    create table test2 (a int, b int, c int, constraint uk_test2 unique (b, c));
    create table test3 (a int, b int, c int, constraint uk_test3b unique (b), constraint uk_test3c unique (c), constraint uk_test3ab unique (a, b));
    

    Use pg_get_indexdef function:

    select pg_get_indexdef(indexrelid) from pg_index where indrelid = 'test'::regclass;
    
                        pg_get_indexdef
    --------------------------------------------------------
     CREATE UNIQUE INDEX pk_test ON test USING btree (a, b)
    (1 row)
    
    
    select pg_get_indexdef(indexrelid) from pg_index where indrelid = 'test2'::regclass;
                         pg_get_indexdef
    ----------------------------------------------------------
     CREATE UNIQUE INDEX uk_test2 ON test2 USING btree (b, c)
    (1 row)
    
    
    select pg_get_indexdef(indexrelid) from pg_index where indrelid ='test3'::regclass;
                          pg_get_indexdef
    ------------------------------------------------------------
     CREATE UNIQUE INDEX uk_test3b ON test3 USING btree (b)
     CREATE UNIQUE INDEX uk_test3c ON test3 USING btree (c)
     CREATE UNIQUE INDEX uk_test3ab ON test3 USING btree (a, b)
    (3 rows)
    

提交回复
热议问题