Inferensys

Prompt

Table Schema Inference Prompt for Unlabeled Data

A practical prompt playbook for using Table Schema Inference Prompt for Unlabeled Data in production AI workflows.
Elegant overhead shot of a polished wooden communal table in a sun-drenched WeWork lounge, laptops and tablets displaying AI workflow dashboards, plants and pendant lights in background.
PROMPT PLAYBOOK

When to Use This Prompt

Determining the right moment to automate schema inference for unlabeled tables and when to rely on manual review or alternative approaches.

Data engineers frequently encounter tables extracted from PDFs, legacy systems, or unstructured sources that arrive without headers, with ambiguous column labels, or with no documented schema. Before these tables can be loaded into a warehouse, joined with other datasets, or validated, someone must determine what each column represents, what data type it holds, and whether it can serve as a primary key. This prompt automates that inference step. It takes raw cell values from an unlabeled table plus optional surrounding document context and produces a proposed schema with column names, data types, primary key candidates, foreign key hypotheses, and confidence scores. The ideal user is a data engineer or pipeline operator who needs a first-pass schema proposal that a human can review and refine, not a guaranteed production schema generated without oversight.

Use this prompt when you have a table with unknown or missing column headers and need to bootstrap a schema for ingestion, when you're processing tables from multiple sources with inconsistent labeling, or when you need to validate an existing schema hypothesis against the actual data. The prompt works best when you can provide at least 10-20 sample rows so the model has enough signal to distinguish IDs from names, dates from timestamps, and measures from dimensions. Providing surrounding document context—such as the paragraph preceding the table, the document title, or a caption—significantly improves accuracy for domain-specific columns. Do not use this prompt when the table schema is already known and you only need type coercion (use a deterministic validator instead), when the data contains PII that cannot be sent to an external model, or when the table has fewer than three rows (insufficient signal for reliable inference).

The prompt outputs a proposed schema with confidence scores per column, not a final production schema. Every output should be treated as a draft that requires human review, especially for columns with confidence below 0.85. For high-stakes pipelines—financial reporting, clinical data, regulatory filings—pair this prompt with a human-in-the-loop review step and a validation harness that checks the proposed schema against known business rules (e.g., 'every table must have a date column' or 'IDs must be unique'). The next section provides the copy-ready prompt template you can adapt for your own pipeline.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Table Schema Inference Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt belongs in your pipeline.

01

Good Fit: Ad-Hoc Data Imports

Use when: You are ingesting unlabeled CSV, Excel, or PDF-derived tables from external partners or legacy systems with no reliable headers. Guardrail: Always run a human review step on the first batch of inferred schemas before automating the pipeline.

02

Bad Fit: Regulated Financial Filings

Avoid when: The table is a 10-K, 10-Q, or other regulatory filing with a strict, known schema. Inference can mislabel line items. Guardrail: Use a deterministic mapping or a fine-tuned extraction model for known document types instead of open-ended inference.

03

Required Inputs

What you need: The raw table data (rows and cells), any surrounding document text for context, and a target output schema format. Guardrail: Strip any PII or sensitive values before sending to the model if using an external API; the model only needs structural patterns, not real data.

04

Operational Risk: Silent Column Misalignment

What to watch: The model confidently assigns a semantic label to the wrong column index, causing downstream data corruption. Guardrail: Implement a post-inference validation step that checks for label-to-data type consistency (e.g., a 'Date' column should contain parseable dates).

05

Operational Risk: Foreign Key Hallucination

What to watch: The model invents a relationship between two tables that does not exist in the source system. Guardrail: Treat all inferred foreign keys as hypotheses. Require a human to confirm or reject them, or cross-reference with actual database constraints if available.

06

Variant: Confidence-Guided Review

Use when: You need to process high volumes but cannot review every table. Guardrail: Modify the prompt to output a per-column and per-relationship confidence score. Route only low-confidence inferences to a human review queue to balance speed and accuracy.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for inferring column names, data types, primary keys, and foreign keys from unlabeled tabular data.

This prompt template is the core instruction set you will send to the model. It is designed to be copied directly into your prompt management system, IDE, or orchestration layer. The template uses square-bracket placeholders for all dynamic inputs. Before sending this to the model, you must replace every placeholder with real data from your ingestion pipeline. The prompt instructs the model to analyze cell patterns, surrounding document context, and value distributions to propose a structured schema with confidence scores.

text
You are a data engineer analyzing an unlabeled table extracted from a document. The table has no headers or has ambiguous column meanings. Your task is to infer a complete schema.

**Input Table Data:**
[INPUT_DATA]

**Surrounding Document Context (if available):**
[DOCUMENT_CONTEXT]

**Domain Hints (e.g., finance, healthcare, logistics):**
[DOMAIN_HINTS]

**Output Requirements:**
Produce a single JSON object conforming to this exact schema:
{
  "proposed_table_name": "string",
  "columns": [
    {
      "column_index": "integer",
      "inferred_name": "string",
      "inferred_data_type": "string (e.g., VARCHAR, INTEGER, DECIMAL, DATE, BOOLEAN)",
      "sample_values": ["string", "string"],
      "null_ratio": "float (0.0 to 1.0)",
      "is_primary_key_candidate": "boolean",
      "is_foreign_key_candidate": "boolean",
      "potential_referenced_table": "string | null",
      "confidence_score": "float (0.0 to 1.0)",
      "reasoning": "string (brief explanation of the inference)"
    }
  ],
  "proposed_primary_key": ["string (column name)"],
  "proposed_foreign_keys": [
    {
      "column": "string",
      "likely_references": "string (table.column)",
      "confidence": "float"
    }
  ],
  "overall_confidence": "float (0.0 to 1.0)",
  "notes": ["string (any ambiguity, missing context, or assumptions made)"]
}

**Constraints:**
[CONSTRAINTS]

**Few-Shot Examples:**
[EXAMPLES]

**Risk Level for this extraction:** [RISK_LEVEL]

To adapt this template, start by populating [INPUT_DATA] with a serialized representation of your table, such as a JSON array of arrays or a CSV string. The [DOCUMENT_CONTEXT] field should contain the text immediately before and after the table in the source document; this is critical for disambiguating columns like 'Date' that could mean 'Transaction Date' or 'Maturity Date'. Use [DOMAIN_HINTS] to pass any known business context from upstream classification. The [CONSTRAINTS] field is where you enforce business rules, such as 'All date columns must be ISO 8601' or 'Currency columns must be identified with their ISO 4217 code'. If you have a library of validated schema examples, populate [EXAMPLES] with one or two input-output pairs to ground the model's behavior. Finally, set [RISK_LEVEL] to low, medium, or high to control the verbosity of the model's reasoning and the strictness of its self-critique. After receiving the output, always validate the JSON structure and check that column_index values are sequential and match the input column count before ingesting the schema into your catalog.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Table Schema Inference Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check the input quality before inference.

PlaceholderPurposeExampleValidation Notes

[TABLE_DATA]

Raw table content extracted from the source document, including all cell values, row positions, and any visible structural cues

{"rows": [["", "Q1", "Q2"], ["Revenue", "$1.2M", "$1.4M"]]}

Must be non-empty. Check that row count matches source. Reject if all cells are empty or only whitespace.

[DOCUMENT_CONTEXT]

Surrounding text, captions, section headings, or footnotes that provide semantic clues about the table's purpose and domain

"Table 3: Quarterly Revenue by Segment (USD in millions)"

Must be a string. Null allowed if no context exists. If provided, verify it does not contain PII or sensitive data before sending to model.

[DOMAIN_HINTS]

Optional keywords, taxonomies, or known entity types that constrain the schema inference to a specific business domain

"financial", "revenue", "quarterly", "segment"

Null allowed. If provided, must be a list of strings. Remove any domain hints that contradict the document context to avoid confusing the model.

[EXPECTED_COLUMN_COUNT]

The number of columns the model should expect, derived from the raw table grid dimensions

4

Must be a positive integer. Validate by counting the maximum number of cells in any row of [TABLE_DATA]. Mismatch indicates a parsing error upstream.

[NULL_REPRESENTATIONS]

A list of strings that represent missing or empty values in the source table, such as dashes, blanks, or placeholder text

["-", "N/A", "", "—"]

Must be a list of strings. Default to ["", "-", "N/A", "null"] if not specified. Incorrect null handling causes type inference failures.

[OUTPUT_SCHEMA]

The target JSON schema the model must conform to, including field names, types, and required constraints for the inferred schema output

{"type": "object", "properties": {"columns": {"type": "array"}}, "required": ["columns", "primary_key_candidates"]}

Must be a valid JSON Schema object. Validate with a schema validator before injection. Reject if required fields are missing or types are unsupported by the target ingestion pipeline.

[CONFIDENCE_THRESHOLD]

The minimum confidence score a column inference must meet to be accepted automatically; lower scores route to human review

0.7

Must be a float between 0.0 and 1.0. Default to 0.7. Set higher (0.85+) for regulated domains. Values below 0.5 produce excessive false positives in review queues.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the schema inference prompt into a production data pipeline with validation, retries, and human review gates.

The schema inference prompt is not a standalone utility; it is a component inside a larger ingestion pipeline. You send raw, unlabeled tabular data to the model and receive a proposed schema. The harness around this prompt is responsible for validating that schema, deciding whether to accept, retry, or escalate, and then applying the schema to downstream normalization and loading steps. Treat the model's output as a proposal, not a committed schema. The harness must enforce structural checks before any data is written to a target system.

Input assembly starts with extracting the raw table from the source document. If the table comes from a PDF, run layout-aware extraction first to produce a grid representation. Pass that grid as [TABLE_GRID] along with any surrounding document context as [DOCUMENT_CONTEXT]. The context should include the page number, section heading, and a few paragraphs of text before and after the table. This context is critical for disambiguating column meanings—a column labeled 'Q1' means something different in a financial statement than in a project plan. Model choice matters: use a model with strong structured output support (GPT-4o, Claude 3.5 Sonnet, or equivalent) and enable JSON mode with the output schema defined in [OUTPUT_SCHEMA]. For high-throughput pipelines, consider batching multiple small tables into a single request to reduce per-call overhead, but keep total token usage under 4K output tokens to maintain schema fidelity.

Validation is the core of the harness. After receiving the proposed schema, run these checks before accepting it: (1) Every column in the input grid must appear in the schema with a non-null inferred_name. (2) Every data_type must be one of your allowed type enum values. (3) Primary key candidates must reference columns that actually exist in the schema. (4) Foreign key candidates must reference valid column pairs and include a confidence score. (5) If confidence for any column falls below your threshold (start with 0.7), route that column to human review. Retry logic: if validation fails on structural grounds (missing columns, invalid types, malformed JSON), retry once with the validation errors appended to [CONSTRAINTS]. If the retry also fails, log the failure and escalate. Do not retry more than twice—diminishing returns set in fast. Human review integration: when confidence is low or validation fails after retries, generate a review payload containing the original table snippet, the model's proposed schema, the specific validation failures, and a simple accept/reject/edit interface. Store all review decisions as ground truth for future fine-tuning or few-shot example selection.

Logging and observability are non-negotiable. Log every inference request with: the prompt version, model identifier, input token count, output token count, latency, validation pass/fail status, confidence distribution across columns, and whether human review was triggered. These logs become your regression test dataset. When you change the prompt or upgrade the model, replay a sample of logged requests and compare schema outputs for drift. Downstream integration: once a schema is accepted, pass it to the normalization step that casts values to the inferred types and maps column names to your canonical data model. If the schema includes foreign key candidates, use them to suggest join paths but do not automatically enforce referential integrity—let a data engineer confirm. The schema output should be versioned alongside the extracted data so that any downstream errors can be traced back to the inference decision that produced them.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the schema inference response. Use this contract to parse the model output, run automated checks, and route low-confidence results for human review.

Field or ElementType or FormatRequiredValidation Rule

proposed_schema

array of objects

Must be a non-empty array. Each object must have the keys 'column_name', 'inferred_type', 'confidence', and 'evidence'.

proposed_schema[].column_name

string

Must be a non-empty string. Should be a valid SQL-like identifier (alphanumeric and underscores). Reject if it contains only generic labels like 'column_1' without strong evidence.

proposed_schema[].inferred_type

string (enum)

Must be one of: 'string', 'integer', 'float', 'boolean', 'date', 'datetime', 'currency', 'percentage', 'unknown'. Reject any value not in this enum.

proposed_schema[].confidence

float

Must be a number between 0.0 and 1.0 inclusive. Values below [CONFIDENCE_THRESHOLD] should trigger a human review flag in the application layer.

proposed_schema[].evidence

string

Must be a non-empty string summarizing the pattern or cell samples used for inference. Check that the string length is greater than 10 characters to avoid empty justifications.

primary_key_candidates

array of strings

If present, each string must match a 'column_name' from 'proposed_schema'. An empty array is allowed and indicates no primary key was found.

foreign_key_relationships

array of objects

If present, each object must have 'source_column' and 'target_table' keys. 'source_column' must match a 'column_name' in 'proposed_schema'. 'target_table' must be a non-empty string.

processing_notes

string

If present, must be a string. Can be used to flag ambiguous columns, missing headers, or data quality issues. No strict format check, but null is allowed if no notes are needed.

PRACTICAL GUARDRAILS

Common Failure Modes

Table schema inference from unlabeled data fails in predictable ways. These are the most common production failure modes and the guardrails that catch them before they corrupt downstream pipelines.

01

Hallucinated Column Names

What to watch: The model invents plausible but incorrect column names when headers are missing or ambiguous, especially for numeric columns with no obvious domain signal. A column of integers might be labeled 'employee_id' when it is actually 'transaction_sequence'. Guardrail: Require the model to output a confidence score per column name and a rationale citing the specific cell patterns or surrounding text that support the inference. Route columns with confidence below 0.7 to human review.

02

Type Confusion in Sparse Columns

What to watch: Columns with many nulls or mixed representations cause the model to infer overly broad types like string when a narrower type such as decimal or date is correct. A column with 90% nulls and a few '2024-01-15' values may be typed as string because the model lacks enough evidence. Guardrail: Implement a two-pass approach. First pass infers types from non-null samples only. Second pass validates inferred types against all values and flags type violations. Use a type_confidence field that degrades with null percentage.

03

Primary Key Misidentification

What to watch: The model selects a column as a primary key candidate because it appears unique in the visible sample, but the column may contain duplicates in the full dataset or may be semantically wrong (e.g., picking a surrogate row number instead of a composite business key). Guardrail: Require the model to propose primary key candidates with explicit uniqueness and non-null checks against the provided sample. Add a composite_key_hint field when single-column keys are insufficient. Never accept a primary key inference without a uniqueness_ratio and null_count in the output.

04

Foreign Key Overreach

What to watch: The model infers foreign key relationships between columns that share similar value ranges but have no actual referential integrity, such as matching a department_id of 1-5 in one table with a priority_level of 1-5 in another. Guardrail: Constrain foreign key inference to cases where the model can cite a specific document context (e.g., a schema description paragraph, a data dictionary snippet, or explicit cross-reference text). Output a relationship_evidence field. If no document context exists, suppress foreign key output entirely rather than guessing.

05

Unit and Scale Blindness

What to watch: Numeric columns are assigned types like integer or decimal without detecting that values represent thousands, millions, percentages, or currency units. A column containing '15.2' could be millions of dollars or a percentage, and the downstream system will misinterpret the magnitude. Guardrail: Add a unit_hint and scale_factor field to the schema output. Prompt the model to scan surrounding document text for unit indicators ('in millions', 'USD', '%', 'bps') and to flag columns where scale is ambiguous with unit_confidence. Route ambiguous-scale columns for human confirmation before ingestion.

06

Header-Detail Row Confusion

What to watch: The model treats category label rows, subtotal rows, or section header rows as data rows, producing a schema that includes non-data artifacts as valid columns. This is common in financial statements where 'Total Revenue' appears as a row label, not a data value. Guardrail: Instruct the model to classify each row as data, header, subtotal, grand_total, or section_label before schema inference. Exclude non-data rows from type inference. Output a row_classification array alongside the schema so downstream consumers can filter appropriately.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the quality of a table schema inference output before integrating it into a production pipeline. Use this rubric to build automated eval checks or guide human review of the model's proposed schema.

CriterionPass StandardFailure SignalTest Method

Column Name Quality

All inferred column names are descriptive, snake_cased, and free of special characters or whitespace.

Column names contain spaces, special characters, or are generic placeholders like 'column_1'.

Regex check on all keys in the proposed schema object against a valid identifier pattern.

Data Type Accuracy

Inferred data type for each column matches the dominant pattern in the sample data (e.g., integer, float, date, string).

A column with 95% numeric values is typed as 'string', or a column with ISO 8601 dates is typed as 'string'.

Parse a sample of values from the source data using the proposed type and assert a success rate above a threshold (e.g., 90%).

Primary Key Candidate Validity

The proposed primary key column has high cardinality (unique values) and no nulls in the sample data.

The proposed primary key contains duplicate or null values in the sample data.

Count distinct values in the source data for the proposed key column and compare to total row count; assert no nulls.

Foreign Key Relationship Soundness

A proposed foreign key relationship is supported by value overlap between the two columns and logical naming (e.g., 'user_id' referencing 'id' in another table).

A foreign key is proposed between columns with zero overlapping values or between columns with unrelated names and contexts.

Compute the Jaccard similarity or overlap coefficient between the two columns' value sets and assert it exceeds a minimum threshold (e.g., 0.1).

Confidence Score Calibration

High-confidence inferences (>0.8) are correct in a spot check, and low-confidence inferences (<0.5) correspond to genuinely ambiguous columns.

A column with an obviously clear type and name is assigned a low confidence score, or a completely ambiguous column is assigned a high confidence score.

Manually label 10-20 columns as 'clear' or 'ambiguous' and check if the model's confidence scores correlate with these labels.

Null Handling

Columns with a high proportion of nulls are flagged with a 'nullable' property set to true and a null percentage estimate.

A column with 80% null values is not flagged as nullable, or the schema implies a NOT NULL constraint on a sparse column.

Assert that any column with a null percentage above a threshold (e.g., 50%) has a 'nullable: true' field in the output.

Contextual Naming

Inferred column names incorporate context from the surrounding document (e.g., 'invoice_date' instead of just 'date' if the document is an invoice).

Column names are generic and ignore document context, such as naming a column 'amount' in a table clearly about invoice line items.

Check if any column name contains a domain term from the provided [DOCUMENT_CONTEXT] or [DOCUMENT_TITLE] placeholder.

Output Schema Validity

The entire output is valid JSON that strictly conforms to the [OUTPUT_SCHEMA] defined in the prompt contract.

The output is missing required fields, contains extra untyped fields, or uses incorrect types (e.g., a string where an array of objects is expected).

Validate the raw model output string against the expected JSON Schema using a standard validator library.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single representative table sample. Remove strict output schema requirements and allow the model to propose column names, types, and relationships in a conversational format. Focus on getting the inference logic right before locking down JSON structure.

Simplify the prompt to:

  • Provide the raw table data as [TABLE_DATA]
  • Ask for proposed column names, data types, and primary key candidates
  • Request a confidence level (high/medium/low) for each inference

Watch for

  • Overconfident type assignments on small samples
  • Missing foreign key suggestions when only one table is provided
  • The model inventing column meanings that sound plausible but aren't grounded in cell values
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.