0

can we print all the tables names who are referenced to a single table via a foreign key in psql

1 Answers1

0

As stated here: https://stackoverflow.com/a/1154078/6932732

SELECT conname,
  pg_catalog.pg_get_constraintdef(r.oid, true) as condef
FROM pg_catalog.pg_constraint r
WHERE r.conrelid = 'Table_Name'::regclass AND r.contype = 'f' ORDER BY 1

By replacing Table_Name with the name of the table you want to exam, you will get the foreign keys and the associated references.

If you want to print the actual names of the referenced tables, you will need a more complex query as stated here: https://stackoverflow.com/a/1152321/6932732

SELECT
    tc.table_schema, 
    tc.constraint_name, 
    tc.table_name, 
    kcu.column_name, 
    ccu.table_schema AS foreign_table_schema,
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
      AND tc.table_schema = kcu.table_schema
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
      AND ccu.table_schema = tc.table_schema
WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name='Table_Name';

By replacing Table_Name with the name of the table you want to exam, you will get the foreign keys and the associated references, while the actual table names will be in in the foreign_table_name column.

Glauvus
  • 96
  • 4