4

I have a database with a lot of tables in it. Some of them have names which start with "mytable_". Those tables have some indexes. Now I need to move those indexes also to different server which has similar tables.

I would like to have a script which will create all those indexes that are in given tables on my local server.

Also I would like to make it this way that if this index is already created it will not crash.

How can it be done in Postgres (pg admin)

1 Answer 1

12

You can use pg_get_indexdef() to extra all the index definitions:

select replace(pg_get_indexdef(format('%I.%I', schemaname, indexname)::regclass), ' INDEX ', ' INDEX IF NOT EXISTS ')||';' as ddl
from pg_indexes
where schemaname = 'public'
  and tablename like 'mytable\_%';

The replace is used to "inject" the IF NOT EXISTS so that the statement won't fail if such an index is already present in the target database.

Just spool the result of that query to a file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.