Figure out if a table has a DELETE on CASCADE

Jos3k4 picture Jos3k4 · Oct 30, 2012 · Viewed 9.2k times · Source

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

Answer

Lukas Eder picture Lukas Eder · Oct 30, 2012

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