Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for existence of index in PostgreSQL [duplicate]

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.

like image 276
Nika_Rika Avatar asked Aug 31 '17 13:08

Nika_Rika


People also ask

How do you check if index exists on a table in Postgres?

If you use psql to access the PostgreSQL database, you can use the \d command to view the index information for a table.

Does index allow duplicate values?

Yes, you can create a clustered index on key columns that contain duplicate values.

How do I view PostgreSQL index?

The SQL shell(psql): If we use psql to retrieve the PostgreSQL database, the \d command is used to view the index data for a table. The pg_indexes view: The pg_indexesview provides us to access useful information on each index in the PostgreSQL database.


1 Answers

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.

like image 171
JGH Avatar answered Sep 20 '22 07:09

JGH