Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Constraints from MySQL Database

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

like image 431
lolajl Avatar asked Jun 11 '10 17:06

lolajl


People also ask

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.

What are the constraints of MySQL?

SQL constraints are used to specify rules for the data in a table. Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted.

Where are constraints stored in MySQL?

It's stored in information_schema. columns.


2 Answers

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' 
like image 113
Senseful Avatar answered Sep 22 '22 04:09

Senseful


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; 
like image 28
Harshith J.V. Avatar answered Sep 19 '22 04:09

Harshith J.V.