List of Constraints from MySQL Database List of Constraints from MySQL Database mysql mysql

List of Constraints from MySQL Database


Use the information_schema.table_constraints table to get the names of the constraints defined on each table:

select *from information_schema.table_constraintswhere constraint_schema = 'YOUR_DB'

Use the information_schema.key_column_usage table to get the fields in each one of those constraints:

select *from information_schema.key_column_usagewhere constraint_schema = 'YOUR_DB'

If instead you are talking about foreign key constraints, use information_schema.referential_constraints:

select *from information_schema.referential_constraintswhere constraint_schema = 'YOUR_DB'


Great answer by @Senseful.

I am presenting modified query for those who are only looking for list of constraint names (and not other details/columns):

SELECT DISTINCT(constraint_name) FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB' ORDER BY constraint_name ASC;


This really helps if you want to see primary and foreign key constraints as well as rules around those constraints such as ON_UPDATE and ON_DELETE and the column and foreign column names all together:

SELECT tc.constraint_schema,tc.constraint_name,tc.table_name,tc.constraint_type,kcu.table_name,kcu.column_name,kcu.referenced_table_name,kcu.referenced_column_name,rc.update_rule,rc.delete_ruleFROM information_schema.table_constraints tcinner JOIN information_schema.key_column_usage kcuON tc.constraint_catalog = kcu.constraint_catalogAND tc.constraint_schema = kcu.constraint_schemaAND tc.constraint_name = kcu.constraint_nameAND tc.table_name = kcu.table_nameLEFT JOIN information_schema.referential_constraints rcON tc.constraint_catalog = rc.constraint_catalogAND tc.constraint_schema = rc.constraint_schemaAND tc.constraint_name = rc.constraint_nameAND tc.table_name = rc.table_nameWHERE tc.constraint_schema = 'my_db_name'

You may even want to add in some further information about those columns, simply add this into the SQL (and select the columns you want):

LEFT JOIN information_schema.COLUMNS cON kcu.constraint_schema = c.table_schemaAND kcu.table_name = c.table_nameAND kcu.column_name = c.column_name