If you don't need this to be portable to another RDBMS (or another major Postgres version) it is faster and simpler to use the catalog tables in pg_catalog
instead of the standard information schema:
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 referenced_table, c.contype DESC;
Returns:
referenced_table |
fk_name |
fk_definition |
Schema1.TableA |
b1_fkey |
FOREIGN KEY ("B_id") REFERENCES "Schema1"."TableA"("A_id") |
You only asked for the first column. I added two columns for context.
This returns all referenced tables by all foreign keys involving the given column name - including FK constraints on multiple columns.
The name is automatically schema-qualified if necessary according to the current search_path
. It is also double-quoted automatically where needed.
Check out details of pg_constraint
and pg_attribute
in the manual. More about object identifier types, too.
Related: