Skip to content

Instantly share code, notes, and snippets.

@jeffjohnson9046
Created May 4, 2020 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffjohnson9046/5cff514a4fd2721e4acfcac56eaa2342 to your computer and use it in GitHub Desktop.
Save jeffjohnson9046/5cff514a4fd2721e4acfcac56eaa2342 to your computer and use it in GitHub Desktop.
Find all the foreign keys in a Postgres database.
-- from here: https://dataedo.com/kb/query/postgresql/list-foreign-keys
select kcu.table_schema || '.' ||kcu.table_name as foreign_table,
'>-' as rel,
rel_tco.table_schema || '.' || rel_tco.table_name as primary_table,
string_agg(kcu.column_name, ', ') as fk_columns,
kcu.constraint_name
from information_schema.table_constraints tco
join information_schema.key_column_usage kcu
on tco.constraint_schema = kcu.constraint_schema
and tco.constraint_name = kcu.constraint_name
join information_schema.referential_constraints rco
on tco.constraint_schema = rco.constraint_schema
and tco.constraint_name = rco.constraint_name
join information_schema.table_constraints rel_tco
on rco.unique_constraint_schema = rel_tco.constraint_schema
and rco.unique_constraint_name = rel_tco.constraint_name
where tco.constraint_type = 'FOREIGN KEY'
group by kcu.table_schema,
kcu.table_name,
rel_tco.table_name,
rel_tco.table_schema,
kcu.constraint_name
order by kcu.table_schema,
kcu.table_name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment