Inferensys

Prompt

Database Migration Test Data Verification Prompt

A practical prompt playbook for generating pre-migration and expected post-migration record pairs, then producing comparison queries to verify data integrity after schema changes.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Database Migration Test Data Verification Prompt.

This prompt is for engineers who are about to execute a schema migration and need to verify that data survived the transformation intact. The job-to-be-done is generating a small, targeted set of pre-migration and expected post-migration record pairs, along with the SQL comparison queries that will prove correctness after the migration runs. The ideal user is a backend engineer, database reliability engineer, or platform developer who already has the DDL for both the old and new schemas and understands the migration logic—column renames, type casts, default value applications, and dropped or added columns.

You should use this prompt when the migration is complex enough that manual spot-checking is risky: think breaking normalizations, splitting or merging columns, changing enum representations, or applying new default values to existing rows. The prompt works best when you provide the exact source and target DDL, the migration rules in plain language, and a representative sample of real source rows. It is not a replacement for a full data diff tool or a migration framework's built-in verification. Do not use this prompt for simple additive migrations (new nullable columns only), for verifying entire production-scale tables, or when you cannot supply concrete source rows. The output is a verification harness, not a migration script.

Before you run this prompt, gather the source table DDL, the target table DDL, a written description of every transformation rule, and at least three representative source rows that exercise different code paths. After you receive the output, treat the generated comparison queries as a starting point: review them for correctness, run them in a staging environment first, and add any edge cases the prompt missed. If the migration involves financial, healthcare, or otherwise regulated data, a human reviewer must sign off on the verification queries before they are used as a gate for production deployment.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Database Migration Test Data Verification Prompt works well and where you should reach for a different tool or add stronger safeguards.

01

Good Fit: Schema Migration Validation

Use when: you have a known DDL change (column rename, type cast, default addition) and need to verify data integrity before and after the migration. The prompt excels at generating paired pre-migration and expected post-migration records plus comparison queries. Guardrail: always provide the exact DDL for both old and new schemas; the prompt cannot infer missing column semantics.

02

Good Fit: Automated CI/CD Migration Gates

Use when: you want to embed data verification into a deployment pipeline. The prompt produces runnable SQL comparison queries that can be executed as part of a migration test suite. Guardrail: wrap the generated queries in a transaction with a rollback and add a row-count assertion before comparing values to catch empty-result false positives.

03

Bad Fit: Unspecified or Implicit Transformations

Avoid when: the migration logic involves application-layer transforms, ETL scripts, or business rules that are not expressed in the DDL. The prompt verifies structural correctness, not semantic correctness of complex data reshaping. Guardrail: for ETL-heavy migrations, pair this prompt with a separate data-diff tool (e.g., data-diff, dbt tests) that compares actual migrated output against expected business rules.

04

Required Inputs: Complete Old and New DDL

Risk: incomplete or partial schema definitions cause the prompt to miss columns, defaults, or constraints, producing verification queries that pass but leave gaps. Guardrail: extract DDL directly from your migration tool (Flyway, Alembic, Liquibase) or database catalog. Do not hand-write partial schemas. Include indexes and constraints if they affect migration behavior.

05

Operational Risk: Large Table Performance

Risk: the generated comparison queries may use full table scans or unoptimized joins that are unsafe on production-scale tables. Guardrail: add LIMIT clauses and WHERE filters to comparison queries before execution. Run against a representative sample or a recent backup, not the live production primary. Review EXPLAIN plans for any query touching tables over 100k rows.

06

Operational Risk: Type Cast Data Loss

Risk: the prompt may generate expected values that assume lossless type conversion (e.g., TEXT to INTEGER) when the actual migration truncates or rejects data. Guardrail: add an explicit pre-migration query that counts rows violating the new type constraint. If the count is non-zero, flag the migration as lossy and require human approval before proceeding.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for generating pre-migration and post-migration record pairs plus comparison queries.

This prompt template is the core instruction you will send to the model. It is designed to accept a source schema, a target schema, and a set of migration rules, then produce a verification dataset and the SQL queries needed to confirm correctness. The template uses square-bracket placeholders so you can swap in your own schemas, constraints, and output format requirements without rewriting the logic.

text
You are a database migration verification engineer. Your task is to generate a test dataset and comparison queries that validate a schema migration.

## INPUTS
- Source Schema (DDL): [SOURCE_DDL]
- Target Schema (DDL): [TARGET_DDL]
- Migration Rules: [MIGRATION_RULES]
- Row Count: [ROW_COUNT]
- Risk Level: [RISK_LEVEL]

## MIGRATION RULES FORMAT
Each rule describes a transformation:
- Column renames: old_name -> new_name
- Type casts: column_name: old_type -> new_type
- Default value application: column_name: DEFAULT [value]
- Dropped columns: column_name: DROPPED
- Added columns: column_name: ADDED [type] [constraints]

## TASK
1. Generate [ROW_COUNT] pre-migration rows that conform to the Source Schema.
2. For each pre-migration row, generate the expected post-migration row by applying the Migration Rules.
3. Produce a set of SQL comparison queries that verify:
   - Row count preservation (unless rules explicitly add or remove rows).
   - Column rename correctness (old column value equals new column value).
   - Type cast correctness (value is valid in target type, no silent truncation).
   - Default value application (NULLs or missing values replaced correctly).
   - Dropped columns are absent from target.
   - Added columns exist with correct type and constraints.

## OUTPUT SCHEMA
Return a JSON object with this structure:
{
  "pre_migration_rows": [
    { "column_name": "value", ... }
  ],
  "expected_post_migration_rows": [
    { "column_name": "value", ... }
  ],
  "comparison_queries": [
    {
      "query_id": "string",
      "check_type": "row_count | column_rename | type_cast | default_value | dropped_column | added_column",
      "description": "string",
      "sql": "string",
      "expected_result": "string"
    }
  ],
  "coverage_summary": {
    "total_rules": <int>,
    "rules_covered": <int>,
    "uncovered_rules": ["string"]
  }
}

## CONSTRAINTS
- Every Migration Rule must be covered by at least one comparison query.
- Pre-migration rows must include edge cases that exercise each rule (e.g., NULL values for default application, boundary values for type casts).
- SQL queries must be executable in a standard SQL environment (PostgreSQL-compatible syntax).
- If [RISK_LEVEL] is "high", include a rollback verification query for each destructive rule.
- Do not include any data that could be real PII. Use synthetic values only.

## EXAMPLES
[EXAMPLES]

To adapt this template, replace each bracketed placeholder with your concrete inputs. For [SOURCE_DDL] and [TARGET_DDL], paste the full CREATE TABLE statements. For [MIGRATION_RULES], use the exact format shown so the model can parse transformations reliably. The [EXAMPLES] placeholder is optional but strongly recommended for complex migrations: provide one or two example rule-to-query pairs to anchor the model's output style. If you need a different output format, modify the OUTPUT SCHEMA block but keep the field-level descriptions so downstream validators can check completeness. After generating the output, run the comparison queries in a test environment before trusting the verification dataset in production migration rehearsals.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the Database Migration Test Data Verification Prompt. Replace each with concrete values before execution. Validation notes describe how to confirm the input is well-formed and safe.

PlaceholderPurposeExampleValidation Notes

[SOURCE_DDL]

Complete DDL for the pre-migration schema

CREATE TABLE users (id INT PRIMARY KEY, full_name VARCHAR(100), is_active TINYINT);

Parse check: must be valid SQL DDL with at least one CREATE TABLE statement. Confirm column count and types are extractable.

[TARGET_DDL]

Complete DDL for the post-migration schema

CREATE TABLE accounts (account_id INT PRIMARY KEY, display_name VARCHAR(150), active BOOLEAN);

Parse check: must be valid SQL DDL. Schema comparison: column count, type changes, and renames must be detectable against [SOURCE_DDL].

[MIGRATION_RULES]

Natural language or structured mapping of schema changes

Rename full_name to display_name. Cast is_active TINYINT to active BOOLEAN (0->false, 1->true). Add default 'unknown' for missing display_name.

Completeness check: every column in [TARGET_DDL] not present in [SOURCE_DDL] must have a rule. Every rename must have an explicit mapping.

[RECORD_COUNT]

Number of pre-migration records to generate

50

Range check: integer between 1 and 10000. Higher counts increase generation time and token usage. Use lower counts for complex schemas.

[EDGE_CASE_RATIO]

Fraction of records that should exercise boundary conditions

0.2

Range check: float between 0.0 and 1.0. A value of 0.2 means 20% of generated records will contain NULLs, max-length strings, or type boundary values.

[OUTPUT_FORMAT]

Target output structure for generated records and queries

JSON with keys: pre_migration_records, expected_post_migration_records, verification_queries

Schema check: must be one of JSON, SQL_INSERT, CSV. If JSON, validate against expected key set. If SQL_INSERT, confirm dialect matches target database.

[VERIFICATION_STRATEGY]

Comparison method for pre- and post-migration records

row_count_match AND checksum_per_row AND type_cast_validation

Enum check: must include at least one of row_count_match, checksum_per_row, type_cast_validation, null_handling_check, default_value_check. Multiple strategies allowed.

[TARGET_DIALECT]

SQL dialect for generated verification queries

PostgreSQL 15

Enum check: must be a recognized dialect (PostgreSQL, MySQL, SQL Server, Oracle, SQLite). Dialect determines quoting, type casting syntax, and function availability in verification queries.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the migration verification prompt into a CI pipeline or manual QA workflow with validation, retries, and human review gates.

This prompt is designed to be called programmatically as part of a database migration verification step, not as a one-off chat interaction. The typical integration point is a CI/CD pipeline stage that runs after migration scripts have been applied to a staging or ephemeral environment. The harness should supply the DDL diff, the migration script, and a sample of pre-migration production records (sanitized if necessary) as inputs. The prompt returns structured JSON containing pre-migration records, expected post-migration records, and comparison SQL queries. The harness must then execute those comparison queries against the actual migrated database and compare results to the expected outputs.

Validation and Execution Flow: Parse the model's JSON output and validate that every expected post-migration record has a corresponding comparison query. Execute each comparison query against the migrated database. If a query returns zero rows (indicating the expected record was not found), log the specific record and column mismatch. For column rename and type cast checks, the harness should run the provided schema introspection queries (e.g., INFORMATION_SCHEMA.COLUMNS checks) and compare the actual column names and data types against the expected post-migration schema. Retry Logic: If the model output fails JSON schema validation, retry once with a stricter prompt that includes the validation error message. If the retry also fails, escalate to a human reviewer with the raw output attached. Logging: Log the prompt version, input hashes, model response, validation results, and comparison query outcomes. This trace is critical for debugging migration issues and for audit evidence in regulated environments.

Model Choice and Tool Use: Use a model with strong SQL generation and structured output capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). Enable JSON mode or structured outputs if the provider supports it, binding the response to a schema that includes pre_migration_records, expected_post_migration_records, and comparison_queries arrays. This prompt does not require RAG or external tool calls during generation—the DDL and migration script are provided inline. However, the harness itself acts as the tool executor for the generated SQL. Human Review Gate: For migrations involving financial data, healthcare records, or irreversible schema changes, configure the harness to pause after generating the verification plan and require a human to approve the comparison queries before execution. This prevents a hallucinated DROP or UPDATE statement from running unchecked. After execution, flag any mismatches for manual triage before the migration is promoted to production.

IMPLEMENTATION TABLE

Expected Output Contract

Define the exact fields, types, and validation rules your application should enforce on the model response before accepting it as a verified migration test record.

Field or ElementType or FormatRequiredValidation Rule

pre_migration_record

JSON object

Must contain all columns from [SOURCE_SCHEMA] with types matching the source DDL. Validate key count equals source column count.

expected_post_migration_record

JSON object

Must contain all columns from [TARGET_SCHEMA] with types matching the target DDL. Validate key count equals target column count.

migration_rule_applied

string

Must be one of: 'rename', 'type_cast', 'default_applied', 'drop', 'add', 'transform', 'no_change'. Validate against allowed enum.

column_mapping

array of objects

Each object must have 'source_column' and 'target_column' string fields. Source column must exist in pre_migration_record. Target column must exist in expected_post_migration_record.

verification_query

string

Must be a valid SQL SELECT statement. Parse check required. Must reference table names from [TARGET_TABLE]. Must include a WHERE clause comparing expected vs actual values.

expected_query_result

string

Must be 'match', 'mismatch', or 'row_missing'. Validate against allowed enum. If 'mismatch', the diff_reason field must be non-null.

diff_reason

string or null

Required when expected_query_result is 'mismatch'. Must describe the specific column and value discrepancy. Null allowed when result is 'match'.

confidence_score

number

Must be between 0.0 and 1.0 inclusive. Represents model's self-assessed confidence in the migration mapping. Retry prompt if below [CONFIDENCE_THRESHOLD].

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when verifying database migration test data and how to guard against it.

01

Schema Drift Between Prompt and Target

What to watch: The DDL schema provided in the prompt becomes stale as the target database evolves. Column renames, type changes, or new constraints introduced after the prompt was written cause verification queries to fail or produce false negatives. Guardrail: Embed a schema hash or version timestamp in the prompt context and validate it matches the target before generating comparison queries. Reject execution on mismatch.

02

Implicit Type Cast Mismatches

What to watch: The model generates comparison queries that assume compatible types across migration boundaries, but the actual migration introduces implicit casts (e.g., VARCHAR to INTEGER, FLOAT to DECIMAL) that produce silent data truncation or rounding errors. Equality checks pass but values are corrupted. Guardrail: Require explicit CAST in all comparison queries and include precision/scale checks for numeric columns. Add a pre-check that enumerates type changes from the migration spec.

03

Default Value Application Gaps

What to watch: The prompt generates verification pairs assuming default values are applied correctly, but the migration script applies defaults inconsistently—some NULLs become defaults, others remain NULL, and some defaults are applied to existing non-NULL values. Guardrail: Generate separate verification queries for columns with new defaults: one checking NULL-to-default conversion, one checking existing values are untouched, and one checking default value correctness against the migration specification.

04

Referential Integrity Blind Spots

What to watch: Verification queries check row counts and column values but miss broken foreign key relationships introduced by migration reordering, truncated cascade chains, or orphaned child records. Data looks correct in isolation but relationships are severed. Guardrail: Include explicit FK existence checks in every verification query set. Generate anti-join queries that find child records with no parent and parent records with missing required children after migration.

05

Large Table Timeout and Partial Comparison

What to watch: Row-by-row comparison queries time out on large tables, causing the verification harness to report success on partial results or fail silently. Engineers assume verification passed when only a fraction of rows were checked. Guardrail: Generate chunked comparison queries with OFFSET/LIMIT or keyset pagination. Include a row-count baseline check before detailed comparison and a summary query that reports total rows compared vs. total rows expected.

06

Encoding and Collation Corruption

What to watch: Migration changes character encoding or collation (e.g., UTF8 to LATIN1, case-insensitive to case-sensitive) and verification queries using simple equality miss silently corrupted characters or changed sort orders. Guardrail: Generate encoding-aware checks that compare byte-level representations for string columns, include collation-sensitive sort verification, and flag any rows where the migrated value differs in length or byte sequence from the source.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for validating the quality and correctness of generated migration verification data before integrating into a CI pipeline or manual review workflow.

CriterionPass StandardFailure SignalTest Method

Schema Mapping Accuracy

Every column rename, type cast, and default value from [MIGRATION_DDL] is reflected in the post-migration record with no missing or extra columns.

Post-migration record contains a column name from the pre-migration schema that should have been renamed; a NOT NULL column is null in the post-migration record.

Diff the column names and types between the generated pre- and post-migration records against the parsed DDL change list.

Data Integrity Preservation

Non-transformed column values in the post-migration record are byte-for-byte identical to the pre-migration record for all rows in [SAMPLE_SIZE].

A VARCHAR value is truncated, a NUMERIC value has lost precision, or a DATE value has shifted by a timezone offset.

Run a checksum comparison (e.g., MD5 of concatenated values) on non-transformed columns between pre- and post-migration pairs.

Type Cast Correctness

Values in cast columns match the target type exactly: INT contains no decimals, BOOLEAN is true/false not 1/0, and TIMESTAMP includes the correct time zone.

A cast column contains the string 'null', a type conversion error string, or a value that violates the target column's CHECK constraint.

Execute a dry-run INSERT of the post-migration record into a temporary table with the new schema and verify no type errors are raised.

Default Value Application

Columns added with DEFAULT constraints in the migration contain the specified default value, not NULL, unless explicitly nullable without a default.

A new NOT NULL column contains NULL, or a default value is applied to a column that should remain NULL based on the migration definition.

Assert that the value in the new column matches the parsed DEFAULT expression from [MIGRATION_DDL] for every generated row.

Referential Integrity

Foreign key values in the post-migration record resolve to existing primary keys in the referenced parent table, with no dangling references introduced.

A foreign key value in the post-migration record is NULL when the column is NOT NULL, or references a non-existent parent ID.

Execute the generated [VERIFICATION_QUERY] which includes a LEFT JOIN to the parent table and checks for NULL matches on the parent side.

Comparison Query Validity

The generated [VERIFICATION_QUERY] executes without syntax errors and returns exactly the rows that differ between pre- and post-migration states.

The query fails with a syntax error, returns an empty set when differences are known to exist, or returns false positives due to a flawed join condition.

Run the query against the generated pre- and post-migration data in a sandboxed database and assert the result set matches a manually computed diff.

Edge Case Coverage

The generated data includes at least one row exercising each edge case specified in [EDGE_CASES]: NULL inputs, empty strings, max-length strings, and boundary numeric values.

All generated rows use safe, mid-range values with no NULLs, empty strings, or boundary values present in the sample.

Scan the generated data for the presence of NULL, empty string, and boundary values as defined in the [EDGE_CASES] specification.

Output Format Compliance

The output strictly follows [OUTPUT_SCHEMA] with all required fields present, no extra fields, and valid JSON types for each field.

The output is missing the 'post_migration_record' array, contains a string where an object is expected, or includes an unlisted field.

Validate the entire output against the [OUTPUT_SCHEMA] JSON Schema using a standard validator (e.g., ajv) and assert no errors.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single migration pair and manual review. Replace [SCHEMA_DIFF] with a plain-English description of changes instead of a formal DDL diff. Skip the comparison query generation and ask only for pre/post record pairs.

Prompt snippet

code
Given this table schema [TABLE_SCHEMA] and these migration changes [SCHEMA_DIFF], generate 5 pre-migration records and their expected post-migration equivalents. Focus on column renames and type casts only.

Watch for

  • Missing type-cast edge cases (e.g., VARCHAR to INTEGER truncation)
  • Default value assumptions that don't match the actual migration script
  • No verification queries to run against the migrated database
Prasad Kumkar

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.