Inferensys

Prompt

Schema Documentation Generation Prompt

A practical prompt playbook for using Schema Documentation Generation Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for generating schema documentation from DDL and system catalogs.

This prompt is designed for data platform engineers and database administrators who need to transform raw Data Definition Language (DDL) statements and system catalog metadata into a comprehensive, human-readable data dictionary. The core job-to-be-done is eliminating the manual, error-prone process of documenting hundreds of tables and columns by producing a structured artifact that captures table purposes, column descriptions, data types, constraints, relationships, and usage notes. The ideal user has access to a database's information schema or a DDL export and needs documentation that can be reviewed by data consumers, analysts, and downstream engineers before being published to an internal data portal or wiki.

Use this prompt when you have a stable or near-stable schema that is ready for documentation. It works best with relational schemas where foreign keys, check constraints, and comments are already defined in the DDL, as the model can infer relationships and constraints directly from the source. The prompt is not suitable for undocumented NoSQL schemas with no formal structure, for schemas still in early prototyping where tables and columns are renamed daily, or for generating documentation that must satisfy regulatory submission requirements without human review. It is also not a replacement for a data catalog tool; it produces a documentation artifact, not a live, queryable metadata service.

Before using this prompt, ensure you have extracted the complete DDL for all target tables, including CREATE TABLE statements, ALTER TABLE additions, comments, and relevant portions of the system catalog such as information_schema.columns and information_schema.table_constraints. The prompt expects this raw input to be provided in the [INPUT] placeholder. If your schema contains Personally Identifiable Information (PII) in column names, comments, or sample data, redact it before passing it to the model. The output is a draft data dictionary that must be reviewed by a human who understands the domain to catch inferred descriptions that may be plausible but incorrect, especially for columns with cryptic or abbreviated names where the model guesses the meaning.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Schema Documentation Generation Prompt delivers reliable value and where it introduces unacceptable risk.

01

Good Fit: Greenfield Schema Documentation

Use when: You have a stable DDL, system catalog, or migration history and need a first draft of a data dictionary. Guardrail: The prompt excels at structuring known information. Always run the completeness harness check to flag undocumented columns before publication.

02

Bad Fit: Undocumented Legacy Systems

Avoid when: The source schema has no comments, no clear naming conventions, and no subject-matter expert available. Risk: The model will hallucinate plausible but incorrect business logic for cryptic column names like FLG_07. Guardrail: Flag all inferred descriptions with [INFERRED - NEEDS SME REVIEW] and block publication until confirmed.

03

Required Inputs

Required: DDL statements, system catalog exports, or migration files. Strongly Recommended: Existing comments, foreign key definitions, and a glossary of business terms. Guardrail: If only bare column names and types are provided, the output must be treated as a skeleton requiring manual annotation, not a finished document.

04

Operational Risk: Schema Drift

Risk: The documentation becomes stale the moment a new migration runs, creating a dangerous gap between docs and reality. Guardrail: Integrate this prompt into a CI/CD pipeline that triggers re-generation on every schema change. Never treat the generated documentation as a static artifact.

05

Operational Risk: Sensitive Column Exposure

Risk: The prompt might document the existence or purpose of columns containing PII, secrets, or sensitive financial data in a broadly accessible wiki. Guardrail: Pre-process the DDL to redact or tag sensitive columns. The prompt harness should include a PII detection step that flags any column name matching sensitive patterns before the output is published.

06

When to Use a Different Tool

Avoid when: You need a real-time, queryable system catalog for an application. Risk: A markdown document is not an API. Guardrail: Use this prompt for human-readable documentation. For programmatic schema discovery, rely on information_schema or a dedicated schema registry, not a generated text file.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating comprehensive schema documentation from DDL and system catalogs.

This prompt template is designed to ingest raw Data Definition Language (DDL) statements and system catalog metadata, producing a structured, human-readable data dictionary. The output is intended for data platform engineers who need to onboard new team members, support downstream consumers, or prepare for an audit. The template uses square-bracket placeholders so you can inject the specific schema artifacts, output format requirements, and any organizational standards without rewriting the core instruction.

text
You are a senior data architect and technical writer. Your task is to generate a complete, accurate data dictionary from the provided database schema artifacts.

## Input
- Source DDL: [DDL_STATEMENTS]
- System catalog metadata (optional): [CATALOG_METADATA]
- Existing documentation fragments (optional): [EXISTING_DOCS]

## Output Schema
Generate a JSON object conforming to this structure:
{
  "database_name": "string",
  "generated_at": "ISO 8601 timestamp",
  "tables": [
    {
      "table_name": "string",
      "purpose": "A concise, business-meaningful description of the table's role.",
      "estimated_rows": "number or null",
      "columns": [
        {
          "column_name": "string",
          "data_type": "string",
          "nullable": true,
          "default_value": "string or null",
          "description": "A clear explanation of what this column stores, including any units, enumerations, or business rules.",
          "foreign_key_reference": "string or null"
        }
      ],
      "primary_key": ["column_name"],
      "unique_constraints": [["column_name"]],
      "indexes": [
        {
          "index_name": "string",
          "columns": ["column_name"],
          "type": "BTREE | HASH | GIN | etc.",
          "purpose": "Why this index exists, referencing specific query patterns if known."
        }
      ],
      "relationships": [
        {
          "type": "BELONGS_TO | HAS_MANY | HAS_ONE",
          "target_table": "string",
          "foreign_key_columns": ["column_name"],
          "description": "A plain-English explanation of the relationship."
        }
      ],
      "usage_notes": "Any critical operational notes, such as expected write frequency, partitioning strategy, or known pitfalls."
    }
  ]
}

## Constraints
- [CONSTRAINTS]
- If no specific constraints are provided, default to: "Derive all descriptions strictly from the DDL, catalog metadata, and provided documentation. Do not invent business logic. If a column's purpose is ambiguous, state 'Ambiguous: [reason]' in the description."

## Examples
[EXAMPLES]

## Risk Level
[RISK_LEVEL]

To adapt this template, replace the placeholders with concrete inputs. [DDL_STATEMENTS] should contain the CREATE TABLE, ALTER TABLE, and CREATE INDEX statements. [CONSTRAINTS] is where you enforce organizational rules, such as 'Use PascalCase for all entity names' or 'Flag any column storing PII with a pii_risk boolean in the description.' The [EXAMPLES] placeholder is critical for teaching the model the desired tone and depth; provide one fully documented table as a few-shot example. Set [RISK_LEVEL] to high if the documentation will be used for audit or compliance, which should trigger stricter validation in the implementation harness. After copying the prompt, always run the output through a schema validator before publishing it to a data catalog.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the Schema Documentation Generation Prompt. Replace each placeholder with concrete values before execution. Validation notes describe how to verify the input is well-formed and safe.

PlaceholderPurposeExampleValidation Notes

[DDL_STATEMENTS]

Complete DDL for all tables, views, and materialized views to document

CREATE TABLE orders ( id UUID PRIMARY KEY, ... ); CREATE VIEW active_orders AS ...

Parse check: must be valid SQL DDL. Empty or truncated DDL should abort. Minimum one CREATE statement required.

[SYSTEM_CATALOG_EXPORT]

System catalog metadata including column types, defaults, nullable flags, and index definitions

SELECT table_name, column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema='public'

Schema check: must include table_name, column_name, data_type, is_nullable columns. Null catalog should abort with missing-input error.

[DATABASE_DIALECT]

Target SQL dialect for type descriptions and syntax in generated documentation

PostgreSQL 16

Enum check: must match a supported dialect list. Unsupported dialects should trigger a warning and fallback to ANSI SQL descriptions.

[DOCUMENTATION_TEMPLATE]

Desired output structure with required sections, field order, and formatting rules

Table Purpose, Column Name, Type, Nullable, Default, Description, Constraints, Usage Notes

Schema check: must be a valid list of section names. Missing required sections should abort. Unknown sections should warn but proceed.

[BUSINESS_CONTEXT]

Domain knowledge about table purposes, column meanings, and business rules not captured in DDL

orders table tracks customer purchases; status 'pending' means payment not yet confirmed

Null allowed: if absent, prompt should flag columns needing human description. Free text but should be under 2000 tokens to avoid context dilution.

[CONSTRAINT_DEFINITIONS]

Primary key, foreign key, unique, check, and exclusion constraint definitions

ALTER TABLE orders ADD CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)

Parse check: must be valid SQL constraint statements. Missing FK definitions should trigger a completeness warning in output.

[INDEX_DEFINITIONS]

All index definitions including partial, expression, and covering indexes

CREATE INDEX idx_orders_status_date ON orders(status, created_at DESC)

Parse check: must be valid CREATE INDEX statements. Empty index list should produce a note that no indexes were documented.

[USAGE_PATTERNS]

Common query patterns, access frequencies, and known performance considerations

orders table is read-heavy; 10K writes/day; frequently joined with customers on customer_id

Null allowed: if absent, usage notes section should be marked as incomplete. Should be structured as list of patterns with access type and frequency.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Schema Documentation Generation Prompt into a reliable, automated pipeline with validation, retries, and human review gates.

This prompt is designed to be the core of an automated documentation pipeline, not a one-off chat interaction. The primary input is a DDL script or a system catalog extract. The pipeline should parse this input, inject it into the [SOURCE_DDL] placeholder, and optionally supply [DIALECT] and [BUSINESS_CONTEXT] from a configuration file or metadata store. The model's output must be treated as a draft that requires structural validation before it can be published to a data catalog or wiki.

The implementation harness should enforce a strict output contract. After the model generates the documentation, a post-processing validator must parse the output—ideally as JSON or a strongly-typed object—and check for the presence of all required fields: table purpose, column descriptions, data types, nullability, default values, primary and foreign key definitions, and index descriptions. If the validator finds missing sections or malformed structures, the harness should trigger a retry loop. A common failure mode is the model omitting columns from large tables; the validator must compare the count of documented columns against the count of columns in the source DDL. For high-stakes schemas (e.g., financial or healthcare data), the harness must route the validated output to a human review queue before publication, flagging any columns where the model's confidence was low or where the description was auto-generated from the column name alone.

For model choice, prefer models with strong structured output capabilities and large context windows to handle extensive DDL. Use the model's native JSON mode or function-calling interface to constrain the output shape, rather than relying solely on the prompt's [OUTPUT_SCHEMA] instructions. Log every generation attempt, the validation result, and the final approved output to an audit table. This traceability is critical for governance and for debugging schema drift. The next step is to integrate this harness into your CI/CD pipeline so that documentation is regenerated whenever a migration script is committed, ensuring the data dictionary never falls out of sync with the live schema.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required fields, types, and validation rules for the generated schema documentation output. Use this contract to parse and validate the model response before ingestion.

Field or ElementType or FormatRequiredValidation Rule

document_title

string

Must not be empty. Must contain the schema or database name provided in [SCHEMA_NAME].

generated_at

ISO 8601 datetime string

Must parse as a valid UTC datetime. Must be within 5 minutes of system clock if generated in real-time.

tables

array of objects

Must be a non-empty array. Each element must conform to the table_object schema defined in [OUTPUT_SCHEMA].

table_object.name

string

Must exactly match a table name from the source [DDL_INPUT] or [CATALOG_INPUT].

table_object.description

string

Must not be empty. Length must be between 10 and 500 characters.

table_object.columns

array of objects

Must contain at least one column. Count must match the column count in the source DDL for that table.

column_object.name

string

Must exactly match a column name from the source DDL for the parent table.

column_object.data_type

string

Must match the data type declared in the source DDL. Normalized form is acceptable (e.g., 'integer' for 'INT').

column_object.nullable

boolean

Must be true if the source DDL allows NULL; otherwise false. No default assumptions allowed.

column_object.description

string

Must not be empty. If no comment exists in the source, the model must generate a plausible description based on the column name and context.

relationships

array of objects

If present, each object must have valid 'child_table', 'child_column', 'parent_table', 'parent_column' fields that reference existing tables and columns.

usage_notes

array of strings

If present, each string must be non-empty. Should contain actionable advice, not generic filler.

PRACTICAL GUARDRAILS

Common Failure Modes

Schema documentation generation fails in predictable ways. These are the most common failure modes when generating data dictionaries from DDL and system catalogs, with practical guardrails to catch them before documentation ships.

01

Hallucinated Column Purposes

What to watch: The model invents plausible-sounding but incorrect business meanings for columns with cryptic names like status_id, type_cd, or ref_val. Without source evidence, the documentation looks authoritative but misleads consumers. Guardrail: Require the prompt to mark any column description not directly traceable to a constraint, comment, or foreign key as [INFERRED - needs human review]. Run a post-generation check that flags all inferred descriptions for manual confirmation.

02

Missing Implicit Relationships

What to watch: The documentation captures explicit foreign keys but misses implicit relationships—convention-based joins, soft references via string matching, or application-enforced integrity rules. Downstream consumers build incomplete lineage. Guardrail: Add a harness step that scans for columns with naming patterns like _id, _key, or _ref that lack corresponding FK definitions and surfaces them as [UNENFORCED RELATIONSHIP] candidates for human review.

03

Constraint Description Drift

What to watch: The model paraphrases CHECK constraints, defaults, or unique indexes in ways that subtly change their meaning—broadening a range, softening a uniqueness condition, or omitting a NULL interaction. Guardrail: Include a validation pass that extracts every constraint from the source DDL and diffs it against the generated description. Flag any constraint whose generated text fails a strict entailment check against the original SQL expression.

04

Stale Catalog Assumptions

What to watch: The prompt runs against a system catalog snapshot that is hours or days old. Generated documentation misses recent migrations, dropped columns, or renamed tables and silently documents a schema that no longer exists. Guardrail: Require a freshness timestamp in the prompt input and include a pre-generation check that compares the catalog snapshot timestamp against the last known migration timestamp. Abort or flag if the catalog is older than the most recent schema change.

05

Enum and Lookup Table Confusion

What to watch: The model conflates small lookup tables with enum types, or treats CHECK-constrained columns as if they reference a lookup table that doesn't exist. Documentation lists valid values that are incomplete, outdated, or sourced from the wrong place. Guardrail: Add explicit instructions to distinguish enum-like constraints from lookup tables by checking for foreign key references. For CHECK constraints with value lists, include the exact constraint expression in the documentation rather than paraphrasing the allowed values.

06

Usage Notes Without Access Pattern Evidence

What to watch: The model generates confident usage notes like "optimized for point reads" or "suitable for range scans" without access to query logs, index definitions, or workload profiles. These notes become accepted as fact and drive incorrect design decisions. Guardrail: Constrain the prompt to only generate usage notes when index definitions or partitioning schemes are present in the input. For all other cases, output [USAGE NOTES REQUIRE QUERY PATTERN ANALYSIS] and defer to a separate query pattern review prompt.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of generated schema documentation before shipping it to a data catalog or handing it off to consumers. Each criterion targets a specific failure mode common in AI-generated data dictionaries.

CriterionPass StandardFailure SignalTest Method

Schema Fidelity

Every table, column, type, and constraint in the output matches the source [DDL_INPUT] exactly. No invented or missing objects.

Column named created_at in source appears as creation_date in output. A NOT NULL constraint is omitted. A table present in the DDL is missing from the documentation.

Parse the output and diff table/column names, types, and constraints against a parsed AST of [DDL_INPUT]. Flag any mismatch.

Constraint Completeness

All PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and NOT NULL constraints from [DDL_INPUT] are documented with their target columns and referenced tables.

A foreign key relationship is described in prose but the REFERENCES clause is missing. A CHECK constraint on a column is not mentioned.

Extract all constraints from [DDL_INPUT] via SQL parser. For each constraint, assert a corresponding entry exists in the output documentation with the correct columns and references.

Relationship Accuracy

All documented table relationships (one-to-many, many-to-many) correctly reflect the foreign key constraints in [DDL_INPUT] and any junction tables.

A relationship is described as one-to-one when a unique constraint is missing. A junction table is described as a direct many-to-many without noting the join table.

For each foreign key, verify the output's relationship type matches the combination of FK and UNIQUE constraints. Check that junction tables are identified correctly.

Column Description Grounding

Every column description is grounded in the column name, data type, constraints, or provided [CONTEXT]. No hallucinated business logic.

A status column of type VARCHAR(20) is described as 'derived from the payment gateway' when no such context was provided. A price column is assumed to be in USD without evidence.

For a sample of columns, trace each description back to the column name, type, constraints, or explicit statements in [CONTEXT]. Flag any claim not supported by these sources.

Usage Note Actionability

Usage notes provide concrete guidance (e.g., 'This table is append-only. Do not update rows.') rather than vague statements (e.g., 'Use this table carefully.').

A usage note says 'This table is important for reporting.' A note on a nullable column says 'May be null' without explaining when or why.

Review each usage note for the presence of a specific action, prohibition, or condition. Flag notes that are generic restatements of the schema.

Enum and Domain Documentation

All ENUM types, CHECK constraints defining allowed values, and domain types are documented with their complete set of valid values or rules.

A column with type ENUM('active', 'inactive', 'suspended') is documented only as 'User status.' The valid values are not listed.

Extract all ENUM definitions and CHECK constraints involving IN lists from [DDL_INPUT]. Assert the output lists the complete set of valid values for each.

Index Documentation

All indexes from [DDL_INPUT] are documented with their type (BTREE, GIN, etc.), columns, and uniqueness. Partial or expression indexes are noted.

A partial index WHERE deleted_at IS NULL is documented as a simple index on the column. The partial clause is omitted.

Parse all CREATE INDEX statements from [DDL_INPUT]. For each, assert the output includes the index name, type, columns, and any WHERE clause.

Nullability and Default Accuracy

Every column's nullability and default value in the output matches [DDL_INPUT]. Columns without explicit defaults are marked as such.

A column defined as DEFAULT CURRENT_TIMESTAMP is documented with no default. A NOT NULL column is marked as nullable.

For each column, compare the output's nullability and default value against the parsed column definition from [DDL_INPUT]. Flag any discrepancy.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single DDL file or catalog extract. Drop the completeness scoring and focus on generating a readable data dictionary. Accept markdown output without strict schema validation.

Watch for

  • Missing relationship documentation when foreign keys are present
  • Column descriptions that parrot the column name instead of adding business meaning
  • Silent omission of tables without primary keys
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.