Find tables that are not referenced by foreign keys in MySQL database

The query below lists tables that are not referenced by foreign keys.

See also:

Query

select 'No FKs >-' as foreign_keys,
    tab.table_schema as database_name,
    tab.table_name
from information_schema.tables tab
left join information_schema.referential_constraints ref
          on ref.unique_constraint_schema = tab.table_schema
          and ref.referenced_table_name = tab.table_name
where tab.table_type = 'BASE TABLE'
      and tab.table_schema not in ('mysql', 'information_schema',
                                   'performance_schema', 'sys')
      and ref.constraint_name is null
     -- and tab.table_schema = 'your database name'
order by tab.table_schema,
         tab.table_name;

Note: if you need the information for a specific database (schema), then uncomment the table_schema line and provide your database name.

Columns

  • foreign_keys - symbol indicating the lack of FK references
  • database_name - name of the database (schema)
  • table_name - name of the table

Rows

  • One row: represents one table
  • Scope of rows: all tables in a database (schema) that are not referenced by foreign keys
  • Ordered by: database name and table name

Sample results

Comments are only visible when the visitor has consented to statistics cookies. To see and add comments please accept statistics cookies.
0
There are no comments. Click here to write the first comment.