Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figure out if a table has a DELETE on CASCADE

Tags:

Can I know if a database have DELETE ON CASCADE with a query?

like image 348
Jos3k4 Avatar asked Oct 30 '12 08:10

Jos3k4


People also ask

How do I check on delete cascade in SQL?

The column - delete_referential_action helps you know if there is a delete on cascade. Save this answer.

What is Cascade delete and when do we check it?

Cascading deletes are needed when a dependent/child entity can no longer be associated with its current principal/parent. This can happen because the principal/parent is deleted, or it can happen when the principal/parent still exists but the dependent/child is no longer associated with it.

Is on delete cascade?

ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted. For example when a student registers in an online learning platform, then all the details of the student are recorded with their unique number/id.

Is cascade a delete rule?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.


1 Answers

Yes. Just query the INFORMATION_SCHEMA

SELECT * FROM information_schema.REFERENTIAL_CONSTRAINTS 

Or more specifically

-- This query will list all constraints, their delete rule,  -- the constraint table/column list, and the referenced table SELECT    r.CONSTRAINT_NAME,   r.DELETE_RULE,    r.TABLE_NAME,   GROUP_CONCAT(k.COLUMN_NAME SEPARATOR ', ') AS `constraint columns`,   r.REFERENCED_TABLE_NAME FROM information_schema.REFERENTIAL_CONSTRAINTS r   JOIN information_schema.KEY_COLUMN_USAGE k   USING (CONSTRAINT_CATALOG, CONSTRAINT_SCHEMA, CONSTRAINT_NAME) -- using MySQL's GROUP BY clause. In other DB's more columns would need to be -- specified! GROUP BY r.CONSTRAINT_CATALOG,          r.CONSTRAINT_SCHEMA,          r.CONSTRAINT_NAME 

Read more about the REFERENTIAL_CONSTRAINTS table in the manual

like image 151
Lukas Eder Avatar answered Sep 20 '22 13:09

Lukas Eder