If you do not need this to be portable to another RDBMS, it is much faster and easier to use the directory tables in pg_catalog instead of the standard information scheme:
SELECT c.confrelid::regclass::text AS referenced_table , c.conname AS fk_name , pg_get_constraintdef(c.oid) AS fk_definition FROM pg_attribute a JOIN pg_constraint c ON (c.conrelid, c.conkey[1]) = (a.attrelid, a.attnum) WHERE a.attrelid = '"Schema2"."TableB"'::regclass -- table name AND a.attname = 'A_Id' -- column name AND c.contype = 'f' ORDER BY conrelid::regclass::text, contype DESC;
Return:
referenced_table | fk_name | fk_definition ------------------+-------------------------+---------------------------------------------- Schema1.TableA | b1_fkey | FOREIGN KEY ("B_id") REFERENCES "Schema1"."TableA"("A_id")
Notes
The additional two columns are for orientation purposes only. According to your Q, you only need the first column.
This returns all referenced tables with all foreign keys containing the specified column name, including FK restrictions for multiple columns.
The name is automatically assigned to the schema or does not match the visibility set by the current search_path . This name is also automatically escaped if necessary (illegal or uppercase, reserved words, ...).
Check out the pg_constraint and pg_attribute in the manual. And more about the types of object identifiers .
on this topic:
Erwin brandstetter
source share