This sql script can help identify FK columns in databases that are missing a constraint.
Created
November 16, 2021 00:51
-
-
Save benrowe/2e220ef71ea75a8be7ae5366800fbdb1 to your computer and use it in GitHub Desktop.
Find missing Foreign Key constraints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simply replace {DB_TABLE} with your database name.