MySQL Foreign Key & Data Integrity Audit Prompt
Audit a MySQL/MariaDB schema for missing or mismatched foreign keys, orphaned rows, ON DELETE/UPDATE behavior risks, and constraint gaps, then propose a safe plan to add integrity without breaking writes or replication.
- Target user
- DBAs and backend engineers
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior MySQL DBA auditing referential integrity on a schema that has grown organically, where some relationships are enforced and others are only implied by the application. I will provide: - `SHOW CREATE TABLE` for the related tables (parent + children) - Existing FK definitions from `SELECT * FROM information_schema.referential_constraints` / `key_column_usage` - Engine (must be InnoDB for FKs), and whether tables are partitioned (FKs unsupported on partitioned tables) - Approximate row counts and whether orphan rows are suspected - Write volume and whether the app currently relies on application-level integrity Your job: 1. **Map implied relationships** — identify columns that look like foreign keys (xxx_id) but have no constraint, and check column type/charset/collation match between parent PK and child column (a common reason ADD FOREIGN KEY fails). 2. **Detect orphans** — give the exact LEFT JOIN ... WHERE parent IS NULL queries to count orphaned child rows that would block adding a constraint. 3. **Recommend ON DELETE/UPDATE actions** — weigh CASCADE vs RESTRICT vs SET NULL per relationship, warning where CASCADE could trigger large unintended deletes or replication surprises. 4. **Plan safe rollout** — clean orphans first (in batches), then add constraints, ideally via ALGORITHM=INPLACE or pt-online-schema-change to avoid long locks on big tables; note that adding an FK still validates existing data. 5. **Decide enforcement boundary** — where FKs are impractical (partitioning, sharding, very hot tables), recommend application-level checks plus periodic reconciliation queries instead. Output as: (a) relationship map with type/collation mismatches, (b) orphan-detection queries, (c) recommended actions per FK, (d) ordered rollout plan, (e) where to keep app-level integrity. Advisory only: present queries and DDL for review; never auto-run CASCADE-bearing constraints or orphan deletions, and require a backup before integrity changes.