List table columns with their foreign keys in PostgreSQL database

Query below lists all columns with their refererence if column has one.

Query

select col.table_schema || '.' || col.table_name as table,
       col.ordinal_position as col_id,
       col.column_name,
       case when kcu.constraint_name is not null then '>-'
            else null
       end as rel,
       rel.table_name as primary_table,
       rel.column_name as primary_column,
       kcu.constraint_name 
from information_schema.columns col
left join (select kcu.constraint_schema, 
                  kcu.constraint_name, 
                  kcu.table_schema,
                  kcu.table_name, 
                  kcu.column_name, 
                  kcu.ordinal_position,
                  kcu.position_in_unique_constraint
           from information_schema.key_column_usage kcu
           join information_schema.table_constraints tco
                on kcu.constraint_schema = tco.constraint_schema
                and kcu.constraint_name = tco.constraint_name
                and tco.constraint_type = 'FOREIGN KEY'
          ) as kcu
          on col.table_schema = kcu.table_schema
          and col.table_name = kcu.table_name
          and col.column_name = kcu.column_name
left join information_schema.referential_constraints rco
          on rco.constraint_name = kcu.constraint_name
          and rco.constraint_schema = kcu.table_schema
left join information_schema.key_column_usage rel
          on rco.unique_constraint_name = rel.constraint_name
          and rco.unique_constraint_schema = rel.constraint_schema
          and rel.ordinal_position = kcu.position_in_unique_constraint
where col.table_schema not in ('information_schema','pg_catalog')
order by col.table_schema,
         col.table_name,
         col_id;

Columns

  • table - schema name and name of the table in database
  • col_id - position of column within a table
  • column_name - name of the column
  • rel - relationship symbol ('>-') indicating foreign key and direction
  • primary_table - referenced table schema name followed by table name
  • primary_column - referenced column if there is any
  • constraint_name - FK constraint name if there is any

Rows

  • One row represents one column
  • Scope of rows: all columns from all tables
  • Ordered by table schema and name, column id in a table

Sample results

Sample result from pagila database with their references: