Skip to content

Instantly share code, notes, and snippets.

@kampta
Created August 23, 2016 10:58
Show Gist options
  • Save kampta/eef66841e0729061cfd36c7fc417122d to your computer and use it in GitHub Desktop.
Save kampta/eef66841e0729061cfd36c7fc417122d to your computer and use it in GitHub Desktop.
postgreSQL - handy queries

Find all indexes in a postgres table

select
    t.relname as table_name,
    i.relname as index_name,
    array_to_string(array_agg(a.attname), ', ') as column_names
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 'test%'
group by
    t.relname,
    i.relname
order by
    t.relname,
    i.relname;

Find all indexes in all tables in a postgres db

select
    t.relname as table_name,
    i.relname as index_name,
    array_to_string(array_agg(a.attname), ', ') as column_names
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'
group by
    t.relname,
    i.relname
order by
    t.relname,
    i.relname;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment