Inferensys

Prompt

Data Type Casting Risk Analysis Prompt

A practical prompt playbook for using Data Type Casting Risk Analysis Prompt in production AI workflows.
Risk analyst performing AI risk assessment on laptop, risk matrices visible, casual office risk session.
PROMPT PLAYBOOK

When to Use This Prompt

Identify when a data type casting risk analysis is the right tool versus when a simpler check or a full migration review is required.

This prompt is designed for data engineers and backend developers who are preparing or reviewing a database migration script that changes a column's data type. The core job-to-be-done is to prevent data corruption, silent truncation, or application errors that result from implicit or explicit type casting. The ideal user has the proposed ALTER TABLE ... ALTER COLUMN statement, the current schema definition, and a clear understanding of the data's business meaning. Use this prompt when the cost of a casting failure is high—for example, in financial, healthcare, or analytics pipelines where precision loss or overflow would corrupt downstream reporting or trigger cascading application failures.

You should not use this prompt for simple, lossless type widening (e.g., SMALLINT to INTEGER) where the risk is near zero, or for reviewing an entire migration script's transaction safety. For those cases, use a targeted prompt like the Transaction Boundary Safety Review or a standard linter. This prompt is also not a substitute for running the migration against a production-like copy. It is a pre-flight risk analysis that generates a structured report and boundary-value test cases, which you must then execute in a dry-run environment. The prompt requires you to provide the exact DDL, the current column's data profile (min, max, avg length, null count), and any known application constraints as the [CONTEXT].

After using this prompt, your next step is to take the generated risk-ranked list and the boundary-value test cases and run them against a staging or snapshot database. The prompt's output is a plan for validation, not the validation itself. If the analysis identifies a 'Critical' risk of silent truncation or overflow, you must add a data backfill or multi-step migration strategy before proceeding. Avoid the temptation to accept a 'Low' risk rating without verifying it against a full data profile, as the model's assessment is only as good as the statistics you provide.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Data Type Casting Risk Analysis Prompt delivers value and where it introduces risk.

01

Good Fit: Pre-Deployment Migration Review

Use when: A PR contains ALTER COLUMN or type-casting DML and the schema holds production data. Guardrail: Run the prompt against the migration SQL and a sample of the target column's actual values to catch truncation or overflow before execution.

02

Bad Fit: Runtime Type Coercion Logic

Avoid when: Reviewing application-layer type casting in ORM models or API serializers. This prompt targets database-level DDL and DML, not code-level type conversion. Guardrail: Route application-layer casting reviews to the Code Smell and Anti-Pattern Detection prompt instead.

03

Required Input: Column Value Sample

Risk: Without actual data samples, the prompt cannot detect values that will silently truncate or overflow. Guardrail: The harness must execute a SELECT DISTINCT or statistical sample query and inject the results into the prompt's [COLUMN_SAMPLE] placeholder before analysis.

04

Required Input: Target Type Specification

Risk: Ambiguous target types (e.g., 'number' vs 'DECIMAL(10,2)') produce vague risk assessments. Guardrail: Always provide the exact target type with precision, scale, and length parameters. The prompt template requires [TARGET_TYPE] as a mandatory field.

05

Operational Risk: Large Table Scans

Risk: The harness query to sample column values may cause performance issues on very large tables. Guardrail: Use TABLESAMPLE or LIMIT-based sampling with a timeout. If sampling fails, flag the analysis as incomplete and escalate to the Large Table ALTER Statement Review prompt.

06

Operational Risk: Implicit Conversion Blind Spots

Risk: The prompt may miss database-specific implicit conversion rules that differ from standard SQL behavior. Guardrail: Include the database engine and version in [DB_ENGINE] context. Pair this prompt with a dry-run migration in a staging environment before production deployment.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for analyzing data type casting risks in migration scripts.

The prompt below is designed to be copied directly into your AI harness, IDE, or evaluation pipeline. It uses square-bracket placeholders for all dynamic inputs so you can substitute actual schema definitions, migration SQL, and risk thresholds without rewriting the core instruction. Every placeholder is documented so you know what to provide and why it matters for the analysis.

text
You are a database migration safety analyst. Your task is to review a proposed column type change and produce a risk-ranked list of potential failures.

## INPUTS
[MIGRATION_SQL]
The ALTER COLUMN or type-casting DDL statement under review.

[SOURCE_SCHEMA]
The current column definition, including data type, precision, scale, collation, and nullability.

[TARGET_SCHEMA]
The proposed column definition after migration.

[TABLE_STATISTICS]
Row count, distinct value count, min/max values, null count, and sample values for the column. Provide as a structured summary.

[APPLICATION_QUERIES]
Relevant application code, ORM model definitions, or query patterns that reference this column. Include any implicit type assumptions.

## CONSTRAINTS
[CONSTRAINTS]
- Maximum risk level to flag: [RISK_THRESHOLD]
- Deployment pattern: [DEPLOYMENT_PATTERN] (e.g., blue-green, rolling, downtime-window)
- Rollback strategy: [ROLLBACK_STRATEGY]
- Special handling required for: [REGULATED_DATA_CLASSIFICATIONS]

## OUTPUT SCHEMA
[OUTPUT_SCHEMA]
Return a JSON object with this structure:
{
  "summary": "One-sentence risk verdict",
  "risk_level": "LOW|MEDIUM|HIGH|CRITICAL",
  "findings": [
    {
      "id": "F-001",
      "category": "TRUNCATION|PRECISION_LOSS|OVERFLOW|IMPLICIT_CONVERSION|NULL_SURPRISE|COLLATION_CHANGE|APPLICATION_BREAK",
      "severity": "LOW|MEDIUM|HIGH|CRITICAL",
      "description": "What could fail and why",
      "affected_rows_estimate": "count or percentage",
      "example_value": "a value that would break",
      "test_query": "SQL to validate this risk in the actual table"
    }
  ],
  "rollback_safety": {
    "is_rollback_safe": true|false,
    "irreversible_operations": ["list any operations that cannot be undone"],
    "rollback_steps": ["ordered steps to reverse the migration if needed"]
  },
  "recommended_pre_flight_checks": ["checks to run before migration"],
  "boundary_value_tests": [
    {
      "test_case": "description",
      "input_value": "value to test",
      "expected_behavior": "what should happen",
      "failure_mode": "what breaks if the cast is wrong"
    }
  ]
}

## INSTRUCTIONS
1. Compare [SOURCE_SCHEMA] to [TARGET_SCHEMA] and identify every semantic difference in the type change.
2. For each difference, determine whether existing data in [TABLE_STATISTICS] could violate the new type constraints.
3. Cross-reference [APPLICATION_QUERIES] to identify code paths that make implicit assumptions about the current type.
4. Rank findings by severity: CRITICAL (guaranteed data loss or outage), HIGH (likely breakage for some rows), MEDIUM (edge-case risk), LOW (cosmetic or unlikely).
5. Generate boundary value test cases that exercise the edges of the new type.
6. Assess rollback safety given [ROLLBACK_STRATEGY] and [DEPLOYMENT_PATTERN].
7. If [REGULATED_DATA_CLASSIFICATIONS] are present, flag any findings that could cause compliance violations.
8. Do not fabricate table statistics or query patterns. If input data is insufficient to assess a risk, note it as "INSUFFICIENT_DATA" with the specific information needed.

To adapt this prompt, replace each placeholder with actual data from your migration tooling. The [TABLE_STATISTICS] placeholder works best when populated from ANALYZE TABLE output or a data profiling query. The [APPLICATION_QUERIES] placeholder should include ORM model field definitions and any raw SQL found via codebase search for the column name. If you cannot provide query patterns, remove that section and add a constraint instructing the model to flag this as a blind spot. For production use, always run the generated test_query values against a staging copy of the database and feed results back into a second-pass review before approving the migration.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Data Type Casting Risk Analysis Prompt. Each variable must be populated before the prompt is assembled and sent. Missing or malformed inputs will cause the prompt to produce unreliable risk rankings.

PlaceholderPurposeExampleValidation Notes

[MIGRATION_SCRIPT]

The full DDL or DML migration script containing the column type change to analyze

ALTER TABLE orders ALTER COLUMN amount TYPE NUMERIC(12,2);

Must be non-empty and contain at least one ALTER COLUMN, ALTER TABLE, or USING clause. Parse check for valid SQL DDL/DML syntax before prompt assembly.

[SOURCE_COLUMN_DEFINITION]

The current column schema including type, precision, scale, length, and constraints before the migration

amount DECIMAL(10,2) NOT NULL DEFAULT 0.00

Must include full type signature. Validate against actual database catalog or schema dump. Null allowed if column is new.

[TARGET_COLUMN_DEFINITION]

The proposed column schema after the migration completes

amount NUMERIC(12,2) NOT NULL DEFAULT 0.00

Must include full type signature. Compare against [SOURCE_COLUMN_DEFINITION] to confirm a type change is actually proposed. Schema check required.

[TABLE_ROW_COUNT]

Approximate number of rows in the target table to assess migration risk scale

14500000

Must be a positive integer. Used to weight overflow and truncation risk. Acceptable as estimate from pg_class reltuples or equivalent. Null allowed for empty tables.

[EXISTING_DATA_SAMPLE]

A representative sample of current column values including boundary cases

["99999999.99", "-0.01", "NULL", "0", "100000000.00"]

Must be a JSON array of stringified values. Include at least 5 values covering min, max, null, zero, and typical. Validate that values match [SOURCE_COLUMN_DEFINITION] type.

[DATABASE_SYSTEM]

The target database engine to determine casting behavior and implicit conversion rules

PostgreSQL 16

Must match a known system: PostgreSQL, MySQL, SQL Server, Oracle, or SQLite with optional version. Used to select type coercion rule set. Enum validation required.

[APPLICATION_CODE_REFERENCES]

Code paths, ORM models, or query patterns that reference this column

models.py:Order.amount (DecimalField), api/v2/orders.py:line 142

Optional but strongly recommended. List of file paths and line references. Null allowed if codebase scan is unavailable. Improves downstream breakage detection.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Data Type Casting Risk Analysis Prompt into a migration review pipeline with validation, retries, and human approval gates.

This prompt is designed to sit inside a pre-deployment migration review workflow, not as a standalone chat. The harness should feed the prompt a structured migration specification (the DDL or ORM migration diff), the current schema metadata (column types, row counts, sample values), and any known application query patterns that reference the affected columns. The prompt returns a risk-ranked list of casting concerns, each with a severity level, a description of the failure mode, and a suggested test case. The harness must validate this output before it reaches a human reviewer or blocks a deployment pipeline.

The implementation should follow a validate → retry → escalate pattern. After receiving the model response, parse the JSON output and validate that every risk entry contains the required fields: risk_id, severity, column_name, current_type, target_type, failure_mode, affected_rows_estimate, and test_case. If validation fails, retry once with an error message appended to the prompt context. If the retry also fails, log the raw response and escalate to a human reviewer with a clear flag that automated analysis was incomplete. For high-risk migrations (tables over 10M rows, financial data, or PII columns), always require human approval regardless of model confidence. The harness should also execute the generated boundary-value test cases against a staging or snapshot environment and attach the results to the review report before it reaches a human.

Model choice matters here. Use a model with strong SQL and type-system reasoning (GPT-4o, Claude 3.5 Sonnet, or equivalent). Avoid small or general-purpose models that may hallucinate type coercion rules. Set temperature=0 for deterministic output. If your migration tooling already produces a structured diff (e.g., Alembic, Flyway, or Liquibase output), parse that into the [MIGRATION_SPEC] placeholder rather than pasting raw SQL. For teams with large schemas, consider a RAG step that retrieves only the relevant table definitions and column statistics before assembling the prompt, keeping context within token limits. Log every run—input spec, model response, validation result, and human decision—for auditability and prompt improvement over time.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the risk analysis output. Use this contract to build a parser, validator, or eval harness before integrating the prompt into a CI pipeline.

Field or ElementType or FormatRequiredValidation Rule

risk_assessment

object

Top-level JSON object. Must contain 'migration_id', 'analysis_timestamp', and 'findings' array.

migration_id

string

Must match the [MIGRATION_ID] input exactly. Non-empty string.

analysis_timestamp

string (ISO 8601)

Must parse as a valid UTC datetime. Reject if timestamp is in the future.

findings

array of objects

Array must contain at least 1 item. Empty array signals a failure to analyze.

findings[].risk_id

string

Unique within the array. Format: 'RISK-###' (e.g., RISK-001).

findings[].severity

string (enum)

Must be one of: 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'. Case-sensitive.

findings[].category

string (enum)

Must be one of: 'TRUNCATION', 'PRECISION_LOSS', 'OVERFLOW', 'IMPLICIT_CONVERSION', 'UNEXPECTED_COERCION'.

findings[].source_column

string

Must match a column name present in the [SCHEMA_DIFF] input context.

findings[].target_type

string

Must be a valid SQL data type string (e.g., 'INTEGER', 'VARCHAR(255)').

findings[].description

string

Must be a non-empty string between 20 and 500 characters. Must reference the specific column and type change.

findings[].test_case

object

Contains 'boundary_value' and 'expected_behavior' fields. Both must be non-empty strings.

findings[].test_case.boundary_value

string

Must be a concrete, executable value (e.g., '32768' for SMALLINT overflow). Not a description.

findings[].test_case.expected_behavior

string

Must describe a specific pass/fail outcome (e.g., 'Should raise an overflow error').

findings[].remediation

string

Must be a non-empty string. If no remediation is possible, value must be 'MANUAL_REVIEW_REQUIRED'.

PRACTICAL GUARDRAILS

Common Failure Modes

Data type casting prompts fail in predictable ways when the model guesses instead of computing, ignores boundary values, or treats precision loss as a minor detail. These cards cover the most frequent failure patterns and how to prevent them before a migration reaches production.

01

Implicit Truncation Blindness

What to watch: The model assumes silent truncation is safe and fails to flag VARCHAR(255) to VARCHAR(50) casts that would silently drop data beyond the new limit. It often treats length reduction as a formatting change rather than a data loss event. Guardrail: Require the prompt to output a count of rows exceeding the target length for every VARCHAR or TEXT size reduction. Feed actual column max-length statistics into the prompt context so the model works from data, not assumptions.

02

Precision Loss Without Magnitude Check

What to watch: When casting FLOAT to INTEGER or DECIMAL(p,s) to a lower-scale type, the model may list precision loss as a theoretical risk without calculating how many rows are affected or whether the loss magnitude is material. A 0.001 rounding error on transaction amounts is different from a 1000-unit truncation. Guardrail: Include a distribution summary of the source column values in the prompt context. Require the output to bucket affected rows by loss magnitude and flag any bucket exceeding a configurable materiality threshold.

03

Overflow Assumption Gaps

What to watch: The model correctly identifies INT to SMALLINT overflow risk but misses BIGINT to INTEGER overflow when the source column contains values that fit today but could grow. It treats current data as the complete risk surface and ignores growth projections or application-level increment patterns. Guardrail: Add a constraint requiring the model to report both current-value overflow risk and projected overflow risk based on maximum observed value growth rate over the last N months. Flag any column where the current max exceeds 50% of the target type range.

04

Implicit Conversion Chain Confusion

What to watch: The model analyzes a single CAST operation in isolation and misses downstream failures caused by implicit conversion chains. A VARCHAR to DATE cast may succeed, but if that DATE is later compared to a TIMESTAMP column, implicit timezone coercion can produce wrong query results without errors. Guardrail: Require the prompt to trace each type change through at least one level of downstream usage. Include schema metadata showing views, computed columns, and foreign key relationships that reference the target column so the model can map the full impact chain.

05

Enum Reordering Without Sort Impact

What to watch: When reviewing ENUM value additions or removals, the model focuses on application compatibility and ignores sort order changes. Adding a value before existing entries shifts ordinal positions, breaking ORDER BY enum_column queries and index ordering assumptions. Guardrail: Add an explicit instruction to report ordinal position changes for every ENUM modification. Require the output to list any query, index, or application code path that relies on ordinal ordering and would silently produce different results after the change.

06

Nullability Change Cascade Miss

What to watch: The model treats a NOT NULL constraint addition as a simple validation change and fails to identify application code paths that insert without the column, rely on DEFAULT being applied, or use ORM patterns that generate INSERT statements omitting nullable columns. The migration succeeds but the application breaks. Guardrail: Require the prompt to cross-reference the column nullability change against application code patterns. Include ORM model definitions and representative INSERT statement samples in the context. Flag any code path that could generate an INSERT without the newly required column.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Data Type Casting Risk Analysis Prompt before integrating it into a CI/CD pipeline or migration review harness. Each criterion targets a specific failure mode common to type-casting analysis.

CriterionPass StandardFailure SignalTest Method

Risk Completeness

Output identifies at least truncation, precision loss, overflow, and implicit conversion risks for every column listed in [MIGRATION_DIFF]

Output omits a risk category known to apply to the source and target types (e.g., missing truncation for FLOAT to INT)

Run prompt against a diff containing a FLOAT(10,2) to INT cast and check for truncation warning

Boundary Value Test Generation

For each high-risk column, output includes at least 3 test cases covering minimum, maximum, and a boundary-adjacent value

Test cases are missing for a column flagged as HIGH risk, or values are outside the valid range of the target type

Parse the [TEST_CASES] block and validate that each HIGH-risk column has >=3 rows with values within target type bounds

Severity Calibration

Severity levels (CRITICAL, HIGH, MEDIUM, LOW) align with data loss potential: CRITICAL for guaranteed loss, HIGH for likely overflow, MEDIUM for precision loss, LOW for safe implicit conversions

A column cast from VARCHAR(255) to VARCHAR(50) with known 200-char values is rated LOW or MEDIUM instead of HIGH or CRITICAL

Provide a diff with a known truncation scenario and assert severity is HIGH or CRITICAL

Row Count Impact

Output includes an estimated or actual row count for each column that would be affected by the cast failure, sourced from [DATA_PROFILE]

Row count is missing, null, or described as 'unknown' when [DATA_PROFILE] contains the necessary COUNT query results

Supply a [DATA_PROFILE] with a COUNT of 12,000 violating rows and assert the output references that count

Implicit Conversion Flagging

Any cast that relies on implicit conversion (e.g., no explicit CAST or TRY_CAST) is flagged with a warning and a recommendation to make it explicit

A migration script using ALTER COLUMN TYPE without USING clause receives no warning about implicit conversion behavior

Submit a diff with ALTER TABLE t ALTER COLUMN c TYPE INT and check for an implicit conversion warning

Rollback Safety Note

For any cast marked as potentially irreversible (e.g., truncation, rounding), output includes a rollback warning and suggests preserving original data in a backup column or table

Irreversible cast is identified but no rollback or data preservation strategy is mentioned

Check output for a diff containing VARCHAR to CHAR(10) cast; assert presence of a rollback or backup recommendation

Output Schema Validity

Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and no extra fields

Output is missing the 'affected_rows_estimate' field, contains a string where an array is expected, or includes hallucinated fields

Parse the full output with a JSON schema validator against the expected contract

No Hallucinated Columns

Every column referenced in the risk analysis exists in the provided [MIGRATION_DIFF]; no fabricated column names or types

Output warns about a 'user_id' column that does not appear in the input diff

Diff the set of column names in the output against the set in the input; assert no additions

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single migration script and a simplified risk schema. Drop the test-case generation section and focus only on the top-5 risk-ranked findings. Accept plain-text output instead of strict JSON.

Watch for

  • Missing precision-loss detection when implicit casts are buried in nested expressions
  • Over-flagging low-risk VARCHAR widening as a concern
  • No boundary-value suggestions, so the reviewer must invent test cases manually
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.