Skip to content

Instantly share code, notes, and snippets.

@luiz
Last active February 2, 2026 19:09
Show Gist options
  • Select an option

  • Save luiz/ac6a16bf19d2e5b867447701d2aee368 to your computer and use it in GitHub Desktop.

Select an option

Save luiz/ac6a16bf19d2e5b867447701d2aee368 to your computer and use it in GitHub Desktop.
Find foreign keys from/to a table (Postgres)
select distinct
fk_tco.table_schema || '.' || fk_tco.table_name as fk_table_name,
'>-' as rel,
pk_tco.table_schema || '.' || pk_tco.table_name as primary_table_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 pk_tco.table_name = 'XXXX' -- enter table name here
--and fk_tco.table_schema = 'schema_name'
order by fk_table_name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment