Find tables without foreign keys in PostgreSQL database

Query below returns all tables without foreign keys.

See also:

Query

select tab.table_schema,
       tab.table_name,
       '>- no FKs' as foreign_keys
       from information_schema.tables tab
where tab.table_schema not in ('information_schema', 'pg_catalog') 
      and tab.table_type ='BASE TABLE'
      and tab.table_schema || '.' || tab.table_name not in
          (select distinct table_schema || '.' || table_name
           from information_schema.table_constraints
           where constraint_type = 'FOREIGN KEY')
order by tab.table_schema,
         tab.table_name;

Columns

  • table_schema - schema name
  • table_name - name of the table
  • foreign_keys - symbol indicating lack of FKs

Rows

  • One row represents one table without foreign keys
  • Scope of rows: all tables that do not refer to other tables
  • Ordered by schema and table name

Sample results

Tables without foreign keys in pagila database: