2

I have a two tables in the database. First table has a foreign key to second table.

Can I get second table name by the foreign key from first table?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
0xAX
  • 20,957
  • 26
  • 117
  • 206

2 Answers2

4

Simpler and faster by casting to regclass:

SELECT conrelid::regclass::text  AS tbl
     , conname                   AS fk_constraint
     , confrelid::regclass::text AS referenced_tbl
FROM   pg_constraint
WHERE  contype = 'f'
AND    conrelid = 'first_table_name'::regclass  -- table name
-- AND conname = 'fk_name' -- optionally restrict to given FK
ORDER  BY conname;

A table name is not necessarily unique. Schema-qualify the table name or rely on the search_path.

Works for any version of Postgres this side of the millenium.

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
3

Yes, you can.

SELECT ct.oid, conname, condeferrable, condeferred, confupdtype, confdeltype, confmatchtype, conkey, confkey, confrelid, nl.nspname as fknsp, cl.relname as fktab, nr.nspname as refnsp, cr.relname as reftab, description, convalidated
      FROM pg_constraint ct
      JOIN pg_class cl ON cl.oid=conrelid
      JOIN pg_namespace nl ON nl.oid=cl.relnamespace
      JOIN pg_class cr ON cr.oid=confrelid
      JOIN pg_namespace nr ON nr.oid=cr.relnamespace
      LEFT OUTER JOIN pg_description des ON (des.objoid=ct.oid AND des.classoid='pg_constraint'::regclass)
     WHERE contype='f' AND ct.conname = 'yourfk_name' -- conrelid = 26941::oid
     ORDER BY conname;

Just valorize yourfk_name with your foreign_key name. Or use oid if prefered.
This works on 9.3 but I think also 9.x.

user_0
  • 3,173
  • 20
  • 33