HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

PostgreSQL - How to list all foreign key link to Primary key of a table

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlprimaryallforeignhowlistlinktablekey

Problem

I have a table res_users with primary key id

I would like to list all the foreign key link to id from all the tables in my database.

Solution

You can query the catalog tables:

SELECT la.attrelid::regclass AS referencing_table,
       la.attname AS referencing_column
FROM pg_constraint AS c
   JOIN pg_index AS i
      ON i.indexrelid = c.conindid
   JOIN pg_attribute AS la
      ON la.attrelid = c.conrelid
         AND la.attnum = c.conkey[1]
   JOIN pg_attribute AS ra
      ON ra.attrelid = c.confrelid
         AND ra.attnum = c.confkey[1]
WHERE c.confrelid = 'res_users'::regclass
  AND c.contype = 'f'
  AND ra.attname = 'id'
  AND cardinality(c.confkey) = 1;

Code Snippets

SELECT la.attrelid::regclass AS referencing_table,
       la.attname AS referencing_column
FROM pg_constraint AS c
   JOIN pg_index AS i
      ON i.indexrelid = c.conindid
   JOIN pg_attribute AS la
      ON la.attrelid = c.conrelid
         AND la.attnum = c.conkey[1]
   JOIN pg_attribute AS ra
      ON ra.attrelid = c.confrelid
         AND ra.attnum = c.confkey[1]
WHERE c.confrelid = 'res_users'::regclass
  AND c.contype = 'f'
  AND ra.attname = 'id'
  AND cardinality(c.confkey) = 1;

Context

StackExchange Database Administrators Q#265732, answer score: 9

Revisions (0)

No revisions yet.