How do I get a list of all constraints from a particular database?
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.
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.
It's stored in information_schema. columns.
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'
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With