Postgres: To get foreign key dependencies

SELECT

    fk_tco.table_schema AS child_schema,

    fk_tco.table_name AS child_table,

    pk_tco.table_schema AS parent_schema,

    pk_tco.table_name AS parent_table,

    rco.constraint_name AS foreign_key_constraint_name

FROM

    information_schema.referential_constraints rco

JOIN

    information_schema.table_constraints fk_tco ON rco.constraint_name = fk_tco.constraint_name

    AND rco.constraint_schema = fk_tco.table_schema

JOIN

    information_schema.table_constraints pk_tco ON rco.unique_constraint_name = pk_tco.constraint_name

    AND rco.unique_constraint_schema = pk_tco.table_schema

WHERE

    fk_tco.constraint_type = 'FOREIGN KEY'

    AND pk_tco.constraint_type = 'PRIMARY KEY' -- Or 'UNIQUE' for unique constraints

    -- Optional: Filter by specific parent table or schema

    -- AND pk_tco.table_name = 'your_parent_table_name'

    -- AND pk_tco.table_schema = 'your_parent_schema_name'

ORDER BY

    child_schema, child_table;

Comments

Popular posts from this blog

Postgres: Clean up stopped replication slot