Skip to content
This repository has been archived by the owner on Oct 4, 2022. It is now read-only.

Commands

Yash edited this page Jun 23, 2015 · 2 revisions

Return all FOREIGN keys inside Database

select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY'

Show constraints on tables command

select concat(table_name, '.', column_name) as 'foreign key',  
concat(referenced_table_name, '.', referenced_column_name) as 'references'
from information_schema.key_column_usage where
referenced_table_name is not null
and table_schema = 'my_database' 
and table_name = 'my_table'

This shows you the SQL statement necessary to receate mytable in its current form. You can see all the columns and their types (like DESC) but it also shows you constraint information (and table type, charset, etc.).

SHOW CREATE TABLE mytable;

One more way

SELECT * FROM information_schema.TABLE_CONSTRAINTS 
WHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' 
AND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'
AND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';

Another way

select
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
where
REFERENCED_TABLE_NAME = '<table>';