How to find all the Foreign Keys that reference a particular table and column in MySQL
How to find all the Foreign Keys that reference a particular table and column in MySQL

How to find all the Foreign Keys that reference a particular table and column in MySQL

Advertisment
Compatible with MySQL and Maria DB

Simply replace  '$TABLE_NAME%' for the name of the table where the original key is located.

 

SELECT
  TABLE_NAME,
  COLUMN_NAME,
  CONSTRAINT_NAME,
  REFERENCED_TABLE_NAME,
  REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = '$TABLE_NAME%'

 

This will return all the tables that use one of the keys from '$TABLE_NAME%' as a foreign key, but if you need to be more specific about a particular key, use the following query, and change  '$KEY'  for the name of column that has the key

 

SELECT
  TABLE_NAME,
  COLUMN_NAME,
  CONSTRAINT_NAME,
  REFERENCED_TABLE_NAME,
  REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME =  '$TABLE_NAME%'
  and REFERENCED_COLUMN_NAME = '$KEY'

 

You can also specify the specific database by adding '$DB_NAME' as shown below

 

SELECT
  TABLE_NAME,
  COLUMN_NAME,
  CONSTRAINT_NAME,
  REFERENCED_TABLE_NAME,
  REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME =  '$TABLE_NAME%'
  and REFERENCED_COLUMN_NAME = '$KEY'
  and TABLE_SCHEMA = '$DB_NAME'

Comments

Get a Quote

Get a Quote