The list of all the queries

Candidate keys and foreign keys of tables that participate in an inheritance hierarchies

Query goal: Find primary key, unique, foreign key, and exclude constraints that have been defined in tables that participate in an inheritance hierarchy. Do not forget to redefine the constraints that are defined on supertables also on their subtables.
Query type: General (Overview of some aspect of the database.)
Query license: MIT License
Data source: system catalog only
SQL query: Click on query to copy it

with constr as (select 
o.conname,
(select nspname from pg_namespace where oid=c.relnamespace) as constr_schema,
c.relname as constr_table, 
c.oid as constr_table_oid,
o.conkey AS constr_col,
case when o.contype='p' then 'PRIMARY KEY' 
when o.contype='u' then 'UNIQUE' 
when o.contype='f' then 'FOREIGN KEY' 
else 'EXCLUDE' END as contype,
exists (select 1 from pg_inherits as i where c.oid=i.inhparent) and not exists (select 1 from pg_inherits as i where c.oid=i.inhrelid) as is_root
from pg_constraint o inner join pg_class c on c.oid = o.conrelid
where o.contype in ('p','u', 'f', 'x') and c.oid in (select inhrelid from pg_inherits union select inhparent from pg_inherits) ),
constr_unnest as (select conname, constr_schema, constr_table, constr_table_oid, constr_col, constr_col_num, ordin, contype, is_root
from constr, unnest(constr.constr_col) with ordinality as k(constr_col_num, ordin)),
constr_with_names as (select conname, constr_schema, constr_table, contype, array_agg(a_key.attname order by ordin) as constr_col, is_root
from constr_unnest k inner join pg_attribute a_key on k.constr_col_num = a_key.attnum and k.constr_table_oid = a_key.attrelid and a_key.attisdropped = false
group by conname, constr_schema, constr_table, contype, is_root)
select conname, constr_schema, constr_table, contype, constr_col, is_root
from constr_with_names
order by constr_schema, constr_table, contype, constr_col;

Collections where the query belongs to

Collection nameCollection description
Find problems by overviewQueries that results point to different aspects of database that might have problems. A human reviewer has to decide based on the results as to whether there are problems or not .

Categories where the query belongs to

Category nameCategory description
Relationships between tablesQueries of this category provide information about how database tables are connected to each other and whether such connections have been explicitly defined and whether it has been done correctly.
Table inheritanceQueries of this category provide information about the inheritance between base tables.
UniquenessQueries of this category provide information about uniqueness constraints (PRIMARY KEY, UNIQUE, EXCLUDE) as well as unique indexes.

Reference materials for further reading

Reference
https://severalnines.com/database-blog/o-ordbms-postgresql-inheritance
https://www.postgresql.org/docs/current/tutorial-inheritance.html

The list of all the queries