0

I'm trying to get indexes, primary keys, and all constraints for a schema in PostgreSQL using standard sql. Most of the posts I'm finding for how to do this use SQL syntax that is specific to PostgreSQL (I'd like to avoid this). This references include the following:

How do I get the primary key(s) of a table from Postgres via plpgsql?

https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns

https://dba.stackexchange.com/questions/214863/how-to-list-all-constraints-of-a-table-in-postgresql

The following is what I am currently using. Do the queries shown below correctly query for the indexes, primary keys, and constraints for a given schema?

-- indexes
select 
    ns.nspname as schema,
    t.relname as table_name,
    i.relname as index_name,
    a.attname as column_name,
    ixs.indexdef as index_definition
from
    pg_index ix 
    join pg_class i on ix.indexrelid = i.oid
    join pg_class t on ix.indrelid = t.oid and t.relkind = 'r'
    join pg_namespace ns on t.relnamespace = ns.oid
    join pg_indexes ixs on 1=1
        and ns.nspname = ixs.schemaname
        and t.relname = ixs.tablename
        and i.relname = ixs.indexname
    join pg_attribute a on 1=1
        and a.attrelid = t.oid
        and a.attnum = any(ix.indkey)
where 1=1
    and ns.nspname = 'webapi'
order by 
    1,2,3,4
;

-- primary keys
select 
    ns.nspname as schema,
    t.relname as table_name,
    i.relname as index_name,
    a.attname as column_name,
    ixs.indexdef as index_definition
from
    pg_index ix 
    join pg_class i on ix.indexrelid = i.oid
    join pg_class t on ix.indrelid = t.oid and t.relkind = 'r'
    join pg_namespace ns on t.relnamespace = ns.oid
    join pg_indexes ixs on 1=1
        and ns.nspname = ixs.schemaname
        and t.relname = ixs.tablename
        and i.relname = ixs.indexname
    join pg_attribute a on 1=1
        and a.attrelid = t.oid
        and a.attnum = any(ix.indkey)
where 1=1
    and ix.indisprimary = true
    and ns.nspname = 'webapi'
order by 
    1,2,3,4
;

-- constraints
select 
    ns.nspname as schema,
    t.relname as table_name,
    con.conname as constraint_name,
    a.attname as column_name,
    con.contype as constraint_type,
    con.*
from
    pg_constraint con
    join pg_class t on con.conrelid = t.oid
    join pg_namespace ns on t.relnamespace = ns.oid
    join pg_attribute a on 1=1
        and a.attrelid = t.oid
        and a.attnum = any(con.conkey)
where 1=1
    and ns.nspname = 'webapi'
order by 
    1,2,3,4
;
John
  • 3,458
  • 4
  • 33
  • 54
  • 1
    Check the information schema, that's way more "standard" than the PostgreSQL internals. https://www.postgresql.org/docs/current/information-schema.html – Frank Heikens Jan 20 '23 at 15:17

0 Answers0