Skip to content

Instantly share code, notes, and snippets.

@benrowe
Created November 16, 2021 00:51
Show Gist options
  • Save benrowe/2e220ef71ea75a8be7ae5366800fbdb1 to your computer and use it in GitHub Desktop.
Save benrowe/2e220ef71ea75a8be7ae5366800fbdb1 to your computer and use it in GitHub Desktop.
Find missing Foreign Key constraints

Find missing Foreign Key constraints in a MySQL database

This sql script can help identify FK columns in databases that are missing a constraint.

SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE, c.COLUMN_TYPE, kcu.* FROM information_schema.COLUMNS c
LEFT OUTER JOIN information_schema.KEY_COLUMN_USAGE kcu ON c.TABLE_SCHEMA = kcu.CONSTRAINT_SCHEMA AND c.TABLE_NAME = kcu.TABLE_NAME AND c.COLUMN_NAME = kcu.COLUMN_NAME
WHERE
c.TABLE_SCHEMA = '{DB_TABLE}' AND
RIGHT(c.COLUMN_NAME, 3) = '_id' AND
kcu.REFERENCED_TABLE_NAME IS NULL
@benrowe
Copy link
Author

benrowe commented Nov 16, 2021

Simply replace {DB_TABLE} with your database name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment