Use this prompt when a proposed schema change—such as a column drop, table rename, or primary key modification—could break existing foreign key relationships. The primary job is to produce a dependency impact report that identifies orphaned records, cascade risks, and constraint violations before the migration reaches production. The ideal user is a backend engineer, data engineer, or DBA who has the proposed DDL and access to current schema metadata, and who needs a structured risk assessment rather than a generic warning.
Prompt
Foreign Key Constraint Validation Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Foreign Key Constraint Validation Prompt.
This prompt is not a replacement for running actual constraint checks against a staging database. It is a reasoning and planning tool that cross-references the proposed change against declared foreign key relationships. You must provide the current schema DDL, the proposed migration DDL, and optionally a sample of referencing table data as [CONTEXT]. The prompt works best when the harness supplies extracted foreign key metadata, row counts, and any known orphan counts before the model sees the input. Do not use this prompt for performance tuning, index strategy, or data type validation—those require separate specialized prompts.
Avoid using this prompt when the schema is not fully described in the input context or when foreign key relationships are enforced only at the application layer without database-level constraints. The model cannot inspect your live database; it reasons only from the metadata you provide. For high-risk migrations on tables containing PII, financial records, or healthcare data, always pair the prompt's output with a manual review step and a dry-run execution against a production-like environment. The next section provides the copy-ready prompt template you can adapt and wire into your migration review pipeline.
Use Case Fit
Where the Foreign Key Constraint Validation Prompt delivers reliable dependency impact reports—and where it introduces risk if applied without the right harness.
Good Fit: Pre-Merge Schema Review
Use when: a migration script proposes adding, dropping, or modifying a column referenced by foreign keys. Guardrail: feed the prompt both the proposed DDL and the current schema metadata so it can cross-reference actual constraints, not guess.
Bad Fit: Live Production Validation
Avoid when: you need real-time enforcement during query execution. Risk: the prompt analyzes static definitions, not runtime referential integrity. Guardrail: pair this prompt with database-level constraint checks; never use it as a substitute for FOREIGN KEY enforcement.
Required Inputs: Schema Introspection Output
What to watch: the prompt cannot inspect your database directly. Guardrail: a harness must extract INFORMATION_SCHEMA or catalog dumps and inject them as [CURRENT_SCHEMA] before the prompt runs. Without this, orphan detection is speculative.
Operational Risk: Cascade Surprises
Risk: the prompt may identify ON DELETE CASCADE chains but miss application-level side effects. Guardrail: always append an application code scan for manual DELETE statements that bypass cascade logic, and flag findings for human review.
Operational Risk: Stale Metadata
Risk: if the schema metadata passed to the prompt is from a different environment or version, the entire report is invalid. Guardrail: the harness must verify metadata freshness with a timestamp check and refuse to run if the schema dump is older than the last migration.
Good Fit: Rollback Planning
Use when: you need to understand which tables are locked together by foreign keys before writing a rollback script. Guardrail: use the prompt's dependency graph output to sequence rollback steps, but require a human to approve any irreversible TRUNCATE or DROP operations.
Copy-Ready Prompt Template
A reusable prompt template for generating a dependency impact report when validating schema changes against existing foreign key relationships.
This prompt template is designed to be the core instruction set you send to an LLM. It takes a proposed schema change and a snapshot of the current database metadata to produce a structured dependency impact report. The report focuses on orphaned records, cascade risks, and constraint violations. The template uses square-bracket placeholders for all dynamic inputs, making it straightforward to integrate into a CI/CD pipeline, a migration review tool, or a manual pre-flight checklist.
textYou are a senior database reliability engineer. Your task is to analyze a proposed schema change against the current database metadata and produce a Foreign Key Dependency Impact Report. # INPUTS - **Proposed Change (DDL):** ```sql [PROPOSED_DDL_STATEMENT]
- Current Schema Metadata (JSON):
The metadata includes table names, columns, data types, and existing foreign key constraints with their delete/update rules.json[CURRENT_SCHEMA_METADATA] - Row Counts (JSON):
Approximate row counts for all tables referenced in the metadata.json[TABLE_ROW_COUNTS]
OUTPUT SCHEMA
You must respond with a single JSON object conforming to this structure: { "analysis_id": "string", "summary": "A one-sentence executive summary of the overall risk.", "findings": [ { "severity": "CRITICAL | HIGH | MEDIUM | LOW", "type": "ORPHANED_RECORDS | CASCADE_RISK | CONSTRAINT_VIOLATION | MISSING_INDEX", "description": "A clear, specific description of the finding.", "affected_objects": ["schema.table.column"], "estimated_impact_rows": "integer or null", "remediation": "A concrete, actionable step to resolve the issue before deployment." } ], "rollback_safety": "SAFE | RISKY | DESTRUCTIVE", "requires_manual_review": true or false }
CONSTRAINTS
- Ground every finding in the provided metadata. Do not speculate about tables or constraints not present in the input.
- If the proposed change adds a foreign key, check that the data types and collations match exactly. Flag any mismatch as a CONSTRAINT_VIOLATION.
- If the proposed change drops a column, check if it is part of any existing foreign key. If so, flag it as a CRITICAL finding.
- For CASCADE_RISK findings, estimate the blast radius by using the provided row counts of child tables.
- If no issues are found, return an empty
findingsarray and asummarystating the change is safe. - Set
requires_manual_reviewtotrueif any finding has a severity of CRITICAL or HIGH.
To adapt this template, replace the placeholders with data from your own systems. The [PROPOSED_DDL_STATEMENT] should be the exact SQL from the pull request or migration file. The [CURRENT_SCHEMA_METADATA] should be a JSON export from your database's information schema, including all relevant tables, columns, and constraints. The [TABLE_ROW_COUNTS] input is critical for the model to estimate the blast radius of a CASCADE operation; without it, the risk assessment is incomplete. For high-risk environments, always set requires_manual_review to true in your application logic if the model fails to do so, and pipe any CRITICAL finding directly to a human approval queue before the migration can proceed.
Prompt Variables
Required inputs for the Foreign Key Constraint Validation Prompt. Each placeholder must be populated by the harness before the prompt is assembled. Missing or malformed inputs will cause unreliable dependency impact reports.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[PROPOSED_DDL] | The full DDL statement or migration script being reviewed for FK impact | ALTER TABLE orders DROP FOREIGN KEY fk_customer_id; | Must be valid SQL DDL. Parse check required. Reject if empty or contains only comments. Strip trailing semicolons for consistency. |
[CURRENT_SCHEMA_DUMP] | Complete DDL export of the target database schema including all tables, FKs, and indexes | CREATE TABLE orders (...); CREATE TABLE customers (...); ALTER TABLE orders ADD CONSTRAINT fk_customer_id FOREIGN KEY... | Must contain valid CREATE TABLE and ALTER TABLE statements. Execute schema introspection via harness. Reject if schema dump is older than 1 hour or missing FK definitions. |
[REFERENTIAL_INTEGRITY_SNAPSHOT] | Runtime output from INFORMATION_SCHEMA or equivalent showing current FK relationships and constraint status | SELECT * FROM information_schema.referential_constraints WHERE constraint_schema = 'public'; | Must include constraint_name, table_name, referenced_table_name, delete_rule, update_rule. Harness must execute this query against target database. Null allowed only for greenfield schemas with zero existing FKs. |
[ORPHAN_DETECTION_QUERY_RESULTS] | Results of COUNT queries checking for existing orphaned rows in child tables before migration | SELECT COUNT(*) FROM orders WHERE customer_id NOT IN (SELECT id FROM customers); | Must be a numeric result set. Harness must execute COUNT queries for every FK relationship in [CURRENT_SCHEMA_DUMP]. Zero-count results are valid. Null indicates query execution failure and must block prompt assembly. |
[TABLE_ROW_COUNTS] | Approximate row counts for all tables referenced in [PROPOSED_DDL] and their related tables | orders: 14.2M rows, customers: 3.1M rows, order_items: 42.8M rows | Must be integer values from pg_class reltuples or equivalent. Harness must refresh counts within 5 minutes of prompt execution. Required for cascade risk estimation. Null not allowed for any table referenced in the DDL. |
[APPLICATION_CODE_REFERENCES] | Grep or AST search results showing application code that references affected tables or columns | app/models/order.rb: belongs_to :customer; app/services/order_service.py: customer_id=... | Must be file paths with line references. Harness must search codebase for table names and FK column names. Empty results are valid and indicate no application-level references found. Null indicates search failure and requires retry. |
[MIGRATION_CONTEXT] | Metadata about the migration: environment, planned execution window, rollback strategy, and change owner | Production migration, window 2025-01-15 02:00-04:00 UTC, rollback via down migration, owner: data-platform-team | Must include environment, window, rollback plan, and owner. Harness must validate that environment matches the schema source. Reject if environment is production and rollback plan is missing or marked 'none'. |
Implementation Harness Notes
How to wire the Foreign Key Constraint Validation Prompt into a schema review pipeline with cross-referencing, validation, and human approval gates.
The Foreign Key Constraint Validation Prompt is not a standalone tool—it is a reasoning step inside a larger harness that must supply actual schema metadata and proposed DDL changes. The prompt alone cannot query your database or parse your migration files. To make it useful, you need a harness that extracts the current foreign key graph, identifies the tables and columns affected by the proposed change, and packages both into the prompt's [CURRENT_SCHEMA] and [PROPOSED_CHANGES] placeholders. Without this cross-reference, the model will produce plausible-sounding but ungrounded analysis.
Build the harness in three stages: extract, assemble, and validate. In the extract stage, query your database's information schema (e.g., INFORMATION_SCHEMA.KEY_COLUMN_USAGE in MySQL/PostgreSQL or sys.foreign_keys in SQL Server) to produce a structured representation of every existing foreign key—source table, source column, target table, target column, and delete/update rule. In parallel, parse the proposed migration script to identify ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY statements, DROP FOREIGN KEY operations, and any column modifications that could break existing references. The assemble stage merges these into the prompt template, adding a [CONSTRAINTS] block that specifies the output must include orphaned row estimates, cascade path analysis, and a severity classification for each finding. The validate stage runs after the model responds, checking that every referenced table and column actually exists in the supplied schema metadata—this catches hallucinated constraints.
For production use, implement a retry loop with escalating context. If the model's output fails validation (e.g., it references a table not in the input schema), re-invoke the prompt with the validation error appended as a [PREVIOUS_ERRORS] block and instruct the model to correct the mistake. Limit retries to two attempts; after that, flag the finding for human review. Log every invocation—input schema hash, proposed change diff, model response, validation results, and retry count—so you can trace false positives and refine the prompt over time. Model choice matters: use a model with strong structured reasoning (GPT-4o, Claude 3.5 Sonnet, or equivalent) because weaker models will miss transitive cascade paths and produce vague severity classifications.
The highest-risk output from this prompt is a false negative—a missed cascade risk or orphaned record scenario that reaches production. Mitigate this by never treating the prompt's output as the final word. Always run the generated dependency impact report through a human review gate for migrations that touch tables with more than a configurable row-count threshold or that modify delete rules. Pair the prompt with a dry-run harness that executes the proposed DDL in a staging environment and runs the model's suggested validation queries (e.g., SELECT COUNT(*) FROM child_table WHERE parent_id NOT IN (SELECT id FROM parent_table)) to confirm orphan estimates. The prompt is a reasoning accelerator, not a replacement for actual constraint enforcement.
Expected Output Contract
Fields, types, and validation rules for the dependency impact report produced by the Foreign Key Constraint Validation Prompt. Use this contract to parse, validate, and store the model output before surfacing it in a review dashboard or CI check.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
dependency_report | JSON object | Top-level key must exist and be a valid JSON object. Parse check. | |
dependency_report.schema_version | string (semver) | Must match expected version string, e.g., '1.0.0'. Schema check. | |
dependency_report.proposed_change_id | string | Must be non-empty and match the [CHANGE_ID] provided in the prompt context. Equality check. | |
dependency_report.orphaned_records | array of objects | Each object must contain 'table', 'column', 'fk_constraint', and 'estimated_count' fields. Schema check on each element. | |
dependency_report.orphaned_records[].estimated_count | integer or null | If not null, must be >= 0. If null, a 'count_unavailable_reason' string field must be present. Conditional check. | |
dependency_report.cascade_risks | array of objects | Each object must contain 'parent_table', 'child_table', 'fk_constraint', 'cascade_rule', and 'risk_description'. Schema check. | |
dependency_report.constraint_violations | array of objects | Each object must contain 'constraint_name', 'violation_type', 'affected_tables', and 'description'. 'violation_type' must be one of ['NOT_NULL', 'UNIQUE', 'CHECK', 'FK_MISMATCH']. Enum check. | |
dependency_report.overall_risk_level | string | Must be one of ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']. Enum check. If 'CRITICAL', 'orphaned_records' or 'constraint_violations' must be non-empty. Conditional check. |
Common Failure Modes
What breaks first when validating foreign key constraints and how to guard against it.
Orphaned Child Records
What to watch: The prompt identifies a foreign key violation but misses that thousands of child rows will become orphaned after a CASCADE operation. The model reports the constraint name without quantifying the data impact. Guardrail: Require the harness to execute COUNT queries for every proposed CASCADE or SET NULL action and inject the row counts into the prompt context before the model generates its report.
Schema Metadata Drift
What to watch: The prompt analyzes a migration against stale schema metadata because the harness pulled the schema snapshot hours ago or from the wrong environment. The model confidently validates constraints that no longer exist. Guardrail: Embed a schema freshness timestamp in the prompt and refuse analysis if the metadata is older than a configurable threshold. Include the source environment name in the output header.
Cross-Schema Blind Spots
What to watch: The prompt only receives the target schema's foreign key definitions and misses references from other schemas or databases that will break when the constraint changes. Guardrail: Extend the harness to introspect all schemas in the instance for inbound foreign key references to the target table and include them as a dedicated section in the prompt context.
Implicit Constraint Assumptions
What to watch: The model assumes a foreign key exists where the application enforces referential integrity in code rather than in the database. It flags a violation that isn't actually enforced at the schema level. Guardrail: Include a list of application-enforced relationships from the team's documentation or ORM model annotations. Instruct the model to distinguish between database-level and application-level constraints in its report.
Cascade Chain Explosions
What to watch: A single CASCADE deletion triggers a chain across multiple tables, but the prompt only analyzes one level deep. The model reports low risk while the actual operation touches millions of rows across five tables. Guardrail: Require the harness to traverse the full foreign key dependency graph and include a multi-level impact tree in the prompt. Flag any cascade chain exceeding a row-count or depth threshold for human review.
Transaction Boundary Mismatch
What to watch: The prompt validates constraint correctness but ignores that the migration script runs outside a transaction or inside a transaction that's too large for the lock duration. The constraint is valid but the deployment fails under load. Guardrail: Include transaction boundary metadata in the prompt context. Instruct the model to flag any constraint validation that requires a separate transaction or exceeds a lock-duration estimate based on table size.
Evaluation Rubric
Use this rubric to evaluate the quality of the Foreign Key Constraint Validation Prompt output before integrating it into a CI pipeline or review workflow. Each criterion maps to a concrete pass standard, a detectable failure signal, and a test method that can be automated or checked manually.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Orphaned Record Detection | Report lists all child tables where [FK_COLUMN] contains values not present in the referenced [PARENT_TABLE].[PARENT_COLUMN], with exact row counts. | Missing child tables, row count of zero when orphans exist, or failure to name the specific FK constraint. | Execute COUNT query with LEFT JOIN WHERE parent IS NULL for each FK; compare counts to report. |
Cascade Risk Classification | Each DELETE/UPDATE rule is classified as CASCADE, SET NULL, NO ACTION, or RESTRICT with a risk level (HIGH/MEDIUM/LOW) and a plain-language consequence. | Rule misclassified, risk level missing, or consequence description is generic and not specific to the table relationship. | Parse DDL for ON DELETE/ON UPDATE clauses; verify classification matches; check that HIGH risk always accompanies CASCADE on high-volume tables. |
Constraint Violation Forecast | Report identifies specific proposed DDL changes that would violate existing FK constraints and explains why the DDL cannot execute. | Report states no violations when DDL would fail, or identifies violations without citing the conflicting constraint name. | Execute proposed DDL in a transaction with a rollback against a staging schema; confirm error message matches reported violation. |
Dependency Graph Completeness | Output includes a complete parent-child dependency list for the target table, including self-referencing FKs and multi-column FKs. | Missing a self-referencing FK, omitting a multi-column FK, or listing tables that do not have a direct FK relationship. | Query information_schema.KEY_COLUMN_USAGE for the target schema; diff the list of constrained tables against the report. |
Impacted Application Code Mapping | Report maps each FK change to application code paths at risk, citing file paths or module names from the provided [CODEBASE_CONTEXT]. | No code references provided when [CODEBASE_CONTEXT] was supplied, or references point to files that do not contain the FK column name. | Grep [CODEBASE_CONTEXT] for the FK column and table names; verify each reported file contains a match. |
Actionable Remediation Steps | For each HIGH severity finding, the report includes a specific, ordered remediation step with a SQL or code snippet template. | Remediation is vague (e.g., 'fix the data'), missing for a HIGH finding, or suggests a destructive operation without a warning. | Review each HIGH finding; confirm a concrete step exists and that the suggested SQL is syntactically valid for the target dialect. |
Schema Metadata Cross-Reference Accuracy | All table names, column names, and constraint names in the report exactly match the provided [SCHEMA_METADATA] input. | Typos, case mismatches, or invented constraint names that do not appear in [SCHEMA_METADATA]. | Exact string match between report identifiers and [SCHEMA_METADATA] keys; flag any identifier not found in the source. |
Output Schema Validity | Output is valid JSON conforming to the [OUTPUT_SCHEMA] with all required fields present and no extra fields. | JSON parse error, missing required field, or null value in a field marked as required. | Validate output against the [OUTPUT_SCHEMA] JSON Schema definition using a standard validator; reject on any error. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single schema file and a lightweight validation harness. Focus on the core dependency report structure without full cross-reference checks. Accept a simplified input format: paste the proposed DDL and a truncated INFORMATION_SCHEMA dump.
codeYou are reviewing a proposed schema change against existing foreign key relationships. [PROPOSED_DDL] [EXISTING_FK_METADATA] Produce a dependency impact report with: - Orphaned records risk - Cascade path analysis - Constraint violation flags
Watch for
- Missing schema metadata causing false negatives on orphan detection
- Overly broad instructions producing narrative instead of structured findings
- No validation of whether the FK metadata actually matches the target environment

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us