Skip to content

Instantly share code, notes, and snippets.

@pashamray
Created November 26, 2023 15:27
Show Gist options
  • Save pashamray/eac6a730b4033f315a5cf9e2c50ca112 to your computer and use it in GitHub Desktop.
Save pashamray/eac6a730b4033f315a5cf9e2c50ca112 to your computer and use it in GitHub Desktop.
check exists foreign keys
SELECT refcons.TABLE_NAME,
       refcons.REFERENCED_TABLE_NAME,
       refcons.CONSTRAINT_NAME,
       keycol.COLUMN_NAME
FROM information_schema.REFERENTIAL_CONSTRAINTS refcons
         JOIN information_schema.KEY_COLUMN_USAGE keycol ON (
            refcons.CONSTRAINT_SCHEMA = keycol.TABLE_SCHEMA AND
            refcons.TABLE_NAME = keycol.TABLE_NAME AND
            refcons.CONSTRAINT_NAME = keycol.CONSTRAINT_NAME)
WHERE refcons.CONSTRAINT_SCHEMA = 'db_name'
  AND (refcons.TABLE_NAME = 'table' OR refcons.REFERENCED_TABLE_NAME = 'table');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment