16

I know how to create indexes

CREATE INDEX ix_dsvtable
  ON public."DsVTable"
  USING btree
  (dind, sec, regind, datind);

And how can I check if index already exists?

I need to check their existence and create them if they don't exist yet.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nika_Rika
  • 613
  • 2
  • 6
  • 29

1 Answers1

54

You can get the list of indexes, their table and column using this query:

select
    t.relname as table_name,
    i.relname as index_name,
    a.attname 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 like 'mytable'
order by
    t.relname,
    i.relname;

From there, you can check existence by index name or involved column(s) and decide to create/skip the index.

JGH
  • 15,928
  • 4
  • 31
  • 48