Inferensys

Prompt

Partial SQL Query Completion Prompt Template

A practical prompt playbook for recovering truncated SQL statements from model outputs and completing them into executable, validated queries.
ML engineer running AI model benchmarks, performance charts on multiple screens, late night home office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, ideal user, required context, and constraints for recovering truncated SQL statements from model outputs.

Use this prompt when a model output containing a SQL query has been cut off by token limits, streaming interruptions, or early stopping, and you need to recover a syntactically valid, executable statement without altering the original intent. The primary user is a data engineer or backend developer who has received a partial SELECT, INSERT, UPDATE, or DELETE statement—often truncated mid-clause—and must complete it for downstream execution against a known database schema. This is not a text-to-SQL generation prompt; it assumes the model already understood the query intent and produced a partial statement that needs structural repair, not semantic reinterpretation.

The prompt works best when you can supply the partial SQL text, the target SQL dialect (e.g., PostgreSQL, MySQL, T-SQL), and the relevant table schemas or DDL. Without schema context, the model may hallucinate column names or infer incorrect join conditions. Do not use this prompt for queries that were truncated before any meaningful clause was produced—if you only have SELECT and nothing else, there is no recoverable intent. Similarly, avoid this prompt when the partial output contains ambiguous or contradictory logic; in those cases, flag for human review rather than attempting automated completion.

Before wiring this into a production pipeline, define clear acceptance criteria: the completed query must parse successfully against the target SQL dialect, reference only columns and tables present in the provided schema, and preserve all filtering, joining, and aggregation logic present in the partial input. The harness should include a syntax validator, a schema-reference checker, and an optional EXPLAIN plan sanity check to catch nonsensical completions. Always log the original partial input alongside the completed output for auditability, and escalate to a human when the model cannot produce a valid completion within two retry attempts.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Partial SQL Query Completion prompt works, where it fails, and what you must provide before using it in a production harness.

01

Good Fit: Token-Limit Truncation

Use when: A model output was cut off mid-query by max_tokens or a streaming interruption, and the partial SQL is syntactically incomplete. Guardrail: Always pass the exact truncation point and the full original prompt context so the completion prompt can preserve intent without hallucinating new clauses.

02

Bad Fit: Ambiguous Intent

Avoid when: The partial query is so incomplete that the intended tables, joins, or filters cannot be inferred from context. Guardrail: If the harness cannot determine the original query's target schema or business logic, escalate for human review instead of attempting probabilistic completion.

03

Required Input: Schema Context

What to watch: Without table schemas, column names, and relationship context, the model will invent plausible but incorrect identifiers. Guardrail: Always include the relevant DDL or schema description as part of the completion prompt's context window to ground column and table references.

04

Operational Risk: Destructive Execution

What to watch: A repaired query that introduces an unintended DROP, DELETE, or cartesian join can cause data loss or performance incidents. Guardrail: Never auto-execute a repaired query. Route all completions through a EXPLAIN plan review, a dry-run sandbox, or a human approval step before execution.

05

Operational Risk: Dialect Drift

What to watch: The completion model may default to a different SQL dialect (e.g., PostgreSQL syntax for a MySQL target) than the partial input. Guardrail: Explicitly specify the target SQL dialect in the completion prompt and validate the output with a dialect-specific parser before accepting the repair.

06

Bad Fit: Multi-Statement Confusion

Avoid when: The truncation point falls between multiple SQL statements, making it unclear which statement was interrupted. Guardrail: Use a pre-processing step to split the partial output into individual statements and only attempt completion on the final, incomplete statement.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for completing truncated SQL statements into executable queries while preserving the original intent.

This prompt template recovers partial SQL statements that were cut off by token limits, streaming interruptions, or model early-stopping. It takes a truncated SQL fragment and the original generation context, then produces a syntactically valid, executable completion that respects the partial intent without altering existing clauses. Use this when your data pipeline receives incomplete SELECT, JOIN, WHERE, or other SQL clauses from model outputs and needs them repaired before execution against a database.

text
You are a SQL completion engine. Your task is to complete a truncated SQL statement into a valid, executable query.

## INPUT
Partial SQL fragment (may end mid-clause):
[PARTIAL_SQL]

## CONTEXT
Original task that generated this SQL:
[ORIGINAL_TASK]

Target SQL dialect:
[SQL_DIALECT]

Schema context (tables, columns, types):
[SCHEMA_CONTEXT]

## CONSTRAINTS
- Preserve all existing tokens in the partial SQL exactly as written. Do not modify, reorder, or delete any part of the provided fragment.
- Complete only the truncated portion. If the fragment ends mid-keyword, mid-identifier, or mid-expression, finish that element before adding any missing clauses.
- Produce a single, syntactically valid SQL statement that can be parsed and executed against the target dialect.
- Do not add clauses, columns, joins, or conditions that are not implied by the partial fragment and the original task context.
- If the partial SQL already contains a complete statement, return it unchanged.
- If the fragment is too ambiguous to complete safely, output a JSON object with "status": "unrecoverable" and "reason": "<explanation>" instead of guessing.

## OUTPUT FORMAT
Return ONLY the completed SQL statement, with no markdown fences, no explanations, and no preamble. If unrecoverable, return ONLY the JSON object described above.

## EXAMPLES

Example 1:
Partial SQL: SELECT user_id, email, created_at FROM users WHERE
Original Task: Get all active users who signed up in the last 30 days
Schema: users(user_id INT, email VARCHAR, created_at TIMESTAMP, status VARCHAR)
Completed SQL: SELECT user_id, email, created_at FROM users WHERE status = 'active' AND created_at >= NOW() - INTERVAL '30 days'

Example 2:
Partial SQL: SELECT o.order_id, c.name, o.total FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.
Original Task: Find orders over $500 from the current quarter
Schema: orders(order_id INT, customer_id INT, total DECIMAL, order_date DATE), customers(id INT, name VARCHAR)
Completed SQL: SELECT o.order_id, c.name, o.total FROM orders o JOIN customers c ON o.customer_id = c.id WHERE o.total > 500 AND o.order_date >= DATE_TRUNC('quarter', CURRENT_DATE)

Example 3:
Partial SQL: SELECT * FROM products WHERE category = 'electronics' AND price
Original Task: (not provided)
Schema: products(id INT, name VARCHAR, category VARCHAR, price DECIMAL, stock INT)
Completed SQL: {"status": "unrecoverable", "reason": "price condition is ambiguous without original task context—could be less than, greater than, equals, or range comparison"}

Adapt this template by replacing the schema context with your actual table definitions, including column types and relationships. The [ORIGINAL_TASK] placeholder is critical for disambiguation—without it, the model cannot infer the intended WHERE conditions, JOIN logic, or aggregation behavior. If your pipeline doesn't capture the original generation task, modify the constraints section to request a conservative completion that only closes open syntactic elements without adding semantic conditions. For high-risk environments where incorrect SQL could modify data, add an explicit constraint requiring the completed query to be read-only (SELECT only) or add a [RISK_LEVEL] placeholder that gates whether INSERT/UPDATE/DELETE completions are permitted.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Partial SQL Query Completion Prompt Template. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[PARTIAL_SQL]

The truncated or incomplete SQL statement that needs completion

SELECT u.id, u.email, o.total FROM users u JOIN orders o ON u.id = o.user_id WHERE o.

Parse check: must be a non-empty string containing SQL keywords (SELECT, FROM, WHERE, etc.). Reject if empty or contains only whitespace.

[SQL_DIALECT]

Target SQL dialect for syntax and function compatibility

PostgreSQL 15

Must match a supported dialect in the harness enum: PostgreSQL, MySQL, SQLite, SQL Server, BigQuery, Snowflake, Redshift, or Generic ANSI SQL. Reject unknown dialects.

[SCHEMA_CONTEXT]

Relevant table definitions, column names, types, and constraints for the partial query

CREATE TABLE users (id INT PRIMARY KEY, email VARCHAR(255)); CREATE TABLE orders (id INT PRIMARY KEY, user_id INT REFERENCES users(id), total DECIMAL(10,2), status VARCHAR(20));

Parse check: must be valid DDL or empty string if no schema context is available. If provided, extract table and column names for reference-integrity validation in output.

[TRUNCATION_POINT]

Description of where the query was cut off and what clause was interrupted

Cut off mid-WHERE clause after 'o.' — likely a column reference or condition is missing

Must be a non-empty string describing the truncation location. Used by the model to understand what needs completion. Reject if null or empty.

[INTENT_DESCRIPTION]

Natural language description of what the query is supposed to accomplish

Get all users with their order totals, filtered by orders placed in the last 30 days with status 'completed'

Must be a non-empty string. Provides semantic grounding for completion. Reject if null or empty — the model needs intent to avoid hallucinating incorrect clauses.

[OUTPUT_FORMAT]

Expected format for the completed SQL response

SQL only, no markdown fences, no explanation

Must be one of: 'sql_only', 'sql_with_explanation', or 'sql_with_fix_notes'. Default to 'sql_only' if not specified. Controls post-processing extraction logic.

[MAX_COMPLETION_TOKENS]

Token budget for the completion response

500

Must be a positive integer. Set based on expected query complexity. Harness should enforce a ceiling (e.g., 2000 tokens) to prevent runaway generation. Null allowed — defaults to model-specific reasonable maximum.

[ADDITIONAL_CONSTRAINTS]

Extra rules for the completion, such as forbidden functions, required patterns, or security boundaries

Do not use subqueries in WHERE clause; prefer JOINs; no DML statements allowed

Optional. If provided, must be a non-empty string. Harness should append these as explicit constraints in the system prompt. Null allowed.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Partial SQL Query Completion prompt into a production application with validation, retries, and safety checks.

Wiring this prompt into an application requires treating it as a recovery step inside a larger SQL generation or repair pipeline, not as a standalone endpoint. The typical flow begins when a model output is flagged as truncated—either by detecting that the response ended mid-token, by checking that the finish_reason is length or max_tokens, or by failing a SQL syntax parser on the raw output. The partial SQL string is extracted and passed into this prompt's [PARTIAL_SQL] placeholder, along with the original [SCHEMA_CONTEXT] (table definitions, column types, foreign keys) and the [ORIGINAL_REQUEST] that produced the partial query. The prompt returns a completed SQL statement, which must then pass through a series of validation gates before it reaches any database execution layer.

The validation harness should include at minimum three checks. First, a syntax validation using the target database's SQL parser (e.g., sqlparse for generic checks, or a dialect-specific parser like pglast for PostgreSQL, sqlfluff for linting). If the completed query fails to parse, the system should retry the prompt once with the parser error message appended to [CONSTRAINTS]. Second, a schema compliance check that verifies all referenced tables, columns, and aliases exist in the provided [SCHEMA_CONTEXT]—this catches hallucinated column names that the completion step might introduce. Third, a query-plan sanity check using EXPLAIN (without executing the query) to detect cartesian products, missing join conditions, or impossible WHERE clauses. If any check fails, log the failure with the partial input, completed output, and validation error for debugging, then either retry with richer context or escalate for human review depending on your [RISK_LEVEL] configuration.

For production deployment, wrap the prompt call in a circuit breaker that limits retries to a configurable maximum (recommended: 2 retries). Use structured logging to capture the finish_reason of the completion call, the parser result, and any schema drift between the original and completed query. If your application executes the repaired SQL automatically, add a mandatory row-count or runtime guard—for example, reject any completed query whose EXPLAIN output estimates more than [MAX_ROWS] or whose planned execution time exceeds [MAX_QUERY_MS]. For read-only workloads, consider running the completed query in a transaction that is rolled back after extracting the result schema to verify column alignment before committing. Never execute a repaired query against a production write database without human approval unless the [RISK_LEVEL] is explicitly set to low and the query type is restricted to SELECT.

Model choice matters here. Use a model with strong SQL generation capabilities and a context window large enough to hold the full schema context plus the partial query. For most production pipelines, a model like gpt-4o or claude-sonnet-4-20250514 provides reliable completion quality. If latency is critical, consider a smaller fine-tuned model trained specifically on your schema and query patterns. In all cases, monitor the completion's token usage—if the completed query itself approaches the model's output token limit, you may need to split the schema context or use a model with a larger output window. The next step after implementing this harness is to build a regression test suite of known truncated queries and verify that the completed outputs are both syntactically valid and semantically equivalent to the intended full queries.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the completed SQL query output. Use this contract to build post-processing validators and eval harnesses before deploying the prompt.

Field or ElementType or FormatRequiredValidation Rule

completed_query

String (single SQL statement)

Must parse successfully using a SQL parser for the target dialect. No trailing or leading text outside the statement.

completion_point

String (exact match of the last 50 characters of [PARTIAL_QUERY])

The output must begin immediately after this string with no duplication, whitespace gap, or reformatting of the partial input.

syntax_check

Boolean

Set to true if the completed query passes syntax validation. If false, the output must be rejected and retried.

intent_preservation

String (enum: 'preserved', 'altered', 'unknown')

Must be 'preserved'. If a validator or human review detects that the completion changes the original SELECT columns, JOIN logic, or WHERE conditions from the partial input, the output is invalid.

query_plan_sanity

String (enum: 'pass', 'warn', 'fail')

Must be 'pass' or 'warn'. A 'fail' result (e.g., cartesian join, missing index on key column, full table scan on large table) requires human review before execution.

unresolved_placeholders

Array of strings

Must be an empty array. Any remaining [PLACEHOLDER] tokens from the partial input that were not resolved indicate an incomplete completion.

security_flags

Array of strings

Must be empty. Any detected DROP, TRUNCATE, INSERT, UPDATE, DELETE, or EXEC statements outside the original partial intent must be flagged and blocked.

completion_confidence

Float (0.0 to 1.0)

If provided, values below 0.7 should trigger a retry or human review. Null is acceptable if the model does not provide a confidence score.

PRACTICAL GUARDRAILS

Common Failure Modes

Partial SQL completion is brittle. The model can hallucinate columns, misinterpret intent, or produce syntactically valid but logically broken queries. These are the most common failure modes and how to guard against them in production.

01

Hallucinated Column and Table Names

What to watch: The model invents column names, table aliases, or joins that don't exist in the schema when completing a truncated query. This is the most common failure mode and produces queries that parse but fail at runtime. Guardrail: Always pass the relevant schema DDL or a verified column list in the prompt context. Run the completed query through an EXPLAIN or dry-run against a read replica before execution. Reject completions that reference identifiers not present in the provided schema.

02

Intent Drift in WHERE Clause Logic

What to watch: The partial query contains a WHERE clause with specific filter conditions, but the completion reverses, broadens, or contradicts the original filtering intent—turning an exclusion into an inclusion or removing a critical date range. Guardrail: Extract the WHERE clause from the partial input and compare it to the completed output. Flag completions where operators change (e.g., = becomes !=) or where conditions are dropped. Use a diff-based eval that requires explicit justification for any removed filter.

03

Broken JOIN Chain Reconstruction

What to watch: The partial query ends mid-JOIN, and the model completes it with incorrect ON conditions, missing intermediate tables, or Cartesian products that explode result sets. Guardrail: Provide foreign key relationships or an entity-relationship summary in the prompt. Validate the completed query's JOIN graph against known relationships. Run EXPLAIN to detect missing join conditions that would cause cross joins. Set a row-estimate threshold and reject queries with unexpectedly large cardinality.

04

Aggregation and GROUP BY Mismatch

What to watch: The partial query includes SELECT columns that imply aggregation, but the completion omits GROUP BY, groups by the wrong columns, or mixes aggregated and non-aggregated expressions in ways that produce silent wrong results instead of errors. Guardrail: Parse the completed query to verify that every non-aggregated SELECT column appears in the GROUP BY clause. Use a SQL parser-based validator rather than relying on model self-checking. Flag completions where the GROUP BY column count doesn't match the non-aggregate column count.

05

Subquery Context Loss

What to watch: The truncation point is inside a subquery or CTE, and the model loses track of the outer query context—completing the subquery in isolation without respecting the correlation columns, EXISTS conditions, or the outer SELECT list. Guardrail: Include the full partial query up to the truncation point with clear markers showing nesting depth. Validate that correlated subquery references resolve to columns available in the outer scope. Test completions against a set of known subquery patterns with expected correlation behavior.

06

Silent Syntax Repair That Changes Semantics

What to watch: The partial query has a minor syntax issue near the truncation point (missing comma, unclosed parenthesis), and the model's completion silently "fixes" it by altering the intended logic rather than preserving the original structure. Guardrail: Never ask the model to fix syntax errors in the partial input—only to complete from the exact truncation point. Use a separate validation step that compares the AST of the partial input prefix against the corresponding prefix of the completed query. Reject completions where the prefix AST diverges.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a completed SQL query before it is released to a production pipeline or human reviewer. Each criterion includes a pass standard, a failure signal, and a test method that can be automated in a harness.

CriterionPass StandardFailure SignalTest Method

Syntactic Validity

Query parses without errors in the target SQL dialect specified in [SQL_DIALECT].

Parser throws a syntax error or unexpected token exception.

Execute a dry-run parse using a SQL parser library matching [SQL_DIALECT]. Check for a non-null AST.

Intent Preservation

The completed query does not alter the logical intent of the partial [INPUT_QUERY]. All original keywords, table references, and column projections are present.

A core clause (SELECT, FROM, WHERE) from the partial input is removed, reordered, or semantically inverted.

Normalize both [INPUT_QUERY] and the completed query to ASTs. Assert that the input AST is a strict subtree of the output AST.

Identifier Integrity

All table and column names in the completed query match the provided [SCHEMA_CONTEXT] exactly. No hallucinated identifiers are introduced.

A table or column name appears in the output that is not present in [SCHEMA_CONTEXT].

Extract all identifiers from the completed query AST. Assert that the set of identifiers is a subset of the identifiers in [SCHEMA_CONTEXT].

Clause Completeness

The query completes the truncated clause and adds only the minimum necessary syntax to form a valid statement. No new, unrelated clauses are invented.

A new WHERE, JOIN, or subquery clause is added that was not implied by the partial input.

Diff the clause types in the input AST against the output AST. Flag any new clause types not required for syntactic closure.

No Data Hallucination

The completed query does not inject hardcoded literal values, filter conditions, or constants unless they are required to close a broken string or value from the partial input.

A new string literal, date, or numeric constant appears in a WHERE or HAVING clause that was not present in the partial input.

Extract all literal nodes from the output AST. Assert that any literal not present in the input AST is strictly required for syntactic validity.

Join Logic Safety

If the partial input contains a truncated JOIN, the completion infers the ON condition from [SCHEMA_CONTEXT] foreign keys or leaves a placeholder comment. It never generates a Cartesian product.

A JOIN is completed without an ON clause, or an ON clause references non-existent columns.

Parse the completed query. If a JOIN clause exists, assert that an ON or USING clause is present and that all referenced columns exist in [SCHEMA_CONTEXT].

Formatting Consistency

The completed query preserves the casing, indentation, and quoting style of the [INPUT_QUERY].

The output switches from lowercase to uppercase keywords or changes identifier quoting mid-query.

Heuristic check: compare the ratio of uppercase keywords and quoted identifiers between the input and output. Flag a deviation greater than 20%.

Executability Check

The completed query executes without runtime errors on a test database instance or returns a valid query plan.

Execution throws a relation-not-found, type-mismatch, or ambiguous-column error.

Run an EXPLAIN or equivalent plan-check command on a test database with the schema from [SCHEMA_CONTEXT]. Assert a successful plan generation.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a simple retry loop. When the model returns a partial SQL query, pass the truncated output directly into the completion prompt without schema validation or query-plan checks. Accept the first syntactically valid completion.

code
[PARTIAL_SQL]

Watch for

  • The model may complete the query with incorrect table or column names not present in the original partial input
  • No guard against hallucinated JOINs or WHERE clauses that change the query's semantic intent
  • Token-limit truncation may recur if the completion itself is long; budget for continuation overhead
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.