Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View all foreign key constraints for entire MySQL database

I have a large database with over 150 tables that I've recently been handed. I'm just wondering if there is an easy way to view all foreign key constraints for the entire DB instead of on a per-table basis.

like image 589
Scott Wolf Avatar asked Apr 21 '10 15:04

Scott Wolf


People also ask

How can I see all foreign keys in MySQL?

To see foreign key relationships of a table: SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA. KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'db_name' AND REFERENCED_TABLE_NAME = 'table_name';

How can I see all constraints in MySQL?

select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME, REFERENCED_TABLE_NAME from information_schema. KEY_COLUMN_USAGE where TABLE_NAME = 'yourTableName'; To display all constraints on a table, implement the above syntax.


2 Answers

You can use the INFORMATION_SCHEMA tables for this. For example, the INFORMATION_SCHEMA TABLE_CONSTRAINTS table.

Something like this should do it:

select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY' 
like image 131
D'Arcy Rittich Avatar answered Oct 06 '22 20:10

D'Arcy Rittich


This is what I prefer to get useful informations:

SELECT CONSTRAINT_NAME,        UNIQUE_CONSTRAINT_NAME,         MATCH_OPTION,         UPDATE_RULE,        DELETE_RULE,        TABLE_NAME,        REFERENCED_TABLE_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = 'your_database_name' 
like image 27
genespos Avatar answered Oct 06 '22 20:10

genespos