0

I am using the PostgreSQL. I want to write a query that returns all the column names having foreign key constraint and also the name of the table these columns they refer to.

1 Answers1

1

As far as I can see, the information_schema views don't give you the column names, so you'll have to use the catalog:

SELECT c.conrelid::regclass AS source_table,
       a.attname AS column_name,
       k.n AS position,
       c.confrelid::regclass AS referenced_table
FROM pg_constraint AS c
   CROSS JOIN LATERAL unnest(c.conkey) WITH ORDINALITY AS k(attnum, n)
   JOIN pg_attribute AS a
      ON k.attnum = a.attnum AND c.conrelid = a.attrelid
WHERE c.contype = 'f'
ORDER BY c.conrelid::regclass::text, k.n;

To get the data for only a specific table, add the following to the WHERE condition:

AND c.conrelid = 'mytable'::regclass
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
  • Where do I put the name of the table for which I want to get the fk columns and the referenced tables? This query runs for all the tables in the current schema I think? – Sakshi Tanwar Nov 04 '20 at 09:37
  • It is for all tables in all schemas, which is what you asked for. I have added a suggestion for an extra `WHERE` condition to my answer. – Laurenz Albe Nov 04 '20 at 09:54