List of Constraints from MySQL Database

MysqlDatabase DesignConstraints

Mysql Problem Overview


How do I get a list of all constraints from a particular database?

Mysql Solutions


Solution 1 - Mysql

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

select *
from information_schema.table_constraints
where 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_usage
where constraint_schema = 'YOUR_DB'

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

select *
from information_schema.referential_constraints
where constraint_schema = 'YOUR_DB'

Solution 2 - Mysql

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;

Solution 3 - Mysql

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_rule

FROM information_schema.table_constraints tc

inner JOIN information_schema.key_column_usage kcu
ON tc.constraint_catalog = kcu.constraint_catalog
AND tc.constraint_schema = kcu.constraint_schema
AND tc.constraint_name = kcu.constraint_name
AND tc.table_name = kcu.table_name

LEFT JOIN information_schema.referential_constraints rc
ON tc.constraint_catalog = rc.constraint_catalog
AND tc.constraint_schema = rc.constraint_schema
AND tc.constraint_name = rc.constraint_name
AND tc.table_name = rc.table_name

WHERE 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 c
ON kcu.constraint_schema = c.table_schema
AND kcu.table_name = c.table_name
AND kcu.column_name = c.column_name

Solution 4 - Mysql

SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = "tabnam";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlolajlView Question on Stackoverflow
Solution 1 - MysqlSensefulView Answer on Stackoverflow
Solution 2 - MysqlHarshith J.V.View Answer on Stackoverflow
Solution 3 - Mysqlfriek108View Answer on Stackoverflow
Solution 4 - MysqlEmEsEnView Answer on Stackoverflow