Skip to content

Instantly share code, notes, and snippets.

@xivSolutions
Last active January 3, 2016 17:49
Show Gist options
  • Save xivSolutions/8498452 to your computer and use it in GitHub Desktop.
Save xivSolutions/8498452 to your computer and use it in GitHub Desktop.
pg Table Foreign Key Relations, includes composite PKs
SELECT
tc.constraint_name key_name,
ctu.table_name parent_table,
tc.table_name child_table,
(SELECT kcu2.column_name
FROM information_schema.table_constraints tc2
INNER JOIN information_schema.Key_column_usage kcu2
ON tc2.table_name = kcu2.table_name AND tc2.constraint_name = kcu2.constraint_name
WHERE tc2.constraint_type = 'PRIMARY KEY' AND tc2.table_name = ctu.table_name) parent_id,
(SELECT kcu.column_name
FROM information_schema.key_column_usage kcu
WHERE kcu.constraint_name = tc.constraint_name AND kcu.table_name = tc.table_name) child_id
FROM information_schema.table_constraints tc
INNER JOIN information_schema.constraint_table_usage ctu
ON ctu.constraint_name = tc.constraint_name
WHERE tc.constraint_type = 'FOREIGN KEY';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment