Production-grade guide to text to sql patterns covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Text-to-SQL patterns describe the repeatable structures for turning natural-language questions into executable queries against a relational database. They matter whenever an application needs to let non-technical users query data without writing SQL, or when building internal tooling that bridges chat interfaces and backend databases. The pattern you choose determines whether the system produces runnable queries on the first pass, or spends most of its time in correction loops.
The most common starting point is a prompt that combines a system-level schema description with a user question, then sends that to an LLM via a standard inference endpoint. The following curl command illustrates the minimal JSON payload structure that most hosted LLMs accept; replace the host and auth headers with your provider’s values:
curl -X POST https://inference.example.com/v1/chat \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $API_KEY" \
-d '{
"model": "general-purpose",
"messages": [
{"role": "system", "content": "You are a SQL generator. Return only a single SELECT statement. Use only the tables and columns listed in the schema. Do not add explanations."},
{"role": "user", "content": "List all customers who live in Seattle and have spent more than $500 in the last year."}
],
"temperature": 0,
"max_tokens": 500
}'
The response body contains a choices array; extract the content field from the first choice. A typical jq one-liner to pull the raw SQL:
curl ... | jq -r '.choices[0].message.content'
Pipe the result directly into psql for execution against a PostgreSQL backend:
curl ... | jq -r '.choices[0].message.content' | psql -U app_user -d production_db -c "$(cat)"
If the generated statement contains a trailing semicolon, psql -c handles it without error. If it lacks one, append it explicitly or rely on psql's default behavior of sending the statement as-is.
Generated SQL frequently contains minor syntax issues, ambiguous column references, or unintended keywords (e.g., DROP, ALTER). A lightweight validation loop can catch these before execution. The Python library sqlparse is widely available and can format or tokenize the statement:
python3 -c "import sqlparse; print(sqlparse.format(open('query.sql').read(), reindent=true, keyword_case='upper'))"
For a pure Bash approach, a simple preflight check can flag statements that start with dangerous DDL keywords:
#!/usr/bin/env bash
QUERY=$(cat)
case "$QUERY" in
*DROP*|*ALTER*|*TRUNCATE*) echo "REFUSED: potentially destructive keyword detected" ; exit 1 ;;
*) echo "PROCEED" ; exit 0 ;;
esac
If the query fails in psql, the error text is produced verbatim by the server. A typical PostgreSQL syntax error reads:
ERROR: syntax error at or near "SELECT"
Position: 7
When this occurs, strip the first statement, re-prompt the LLM with the error appended, and ask for a corrected version. Many teams store a small set of “repair prompts” that describe the failure mode and request a rewritten query limited to the previously observed error class.
The quality of a generated query is bounded by how much of the database schema the LLM sees. A common pattern is to introspect only the tables and columns relevant to the user’s intent, rather than dumping the entire schema. The following psql commands extract a minimal description:
psql -U app_user -d production_db -c "\dt" # list all tables
psql -U app_user -d production_db -c "\d customers" # describe a specific table
Output from \d looks like:
Table "public.customers"
Column | Type | Collation | Nullable | Default
------------+---------+-----------+----------+-----------------------------------
id | integer | | not null | nextval('customers_id_seq'::regclass)
name | text | | |
city | text | | |
created_at | timestamp with time zone | | | now()
Format this output as a compact markdown or JSON fragment and embed it in the system prompt. When the schema grows beyond a few thousand tokens, prune by selecting only tables referenced in the user’s query keywords, or by using column-level type information without full row-level defaults. A practical rule of thumb: if the formatted schema exceeds 4000 tokens, the LLM will truncate the prompt context, and the generated query will reference columns that no longer exist.
Once the query runs, the output format often needs to match the downstream consumer—CLI, web UI, or API response. psql offers flags to produce machine-readable output:
psql -U app_user -d production_db -t -A -F '|' -c "SELECT id, name, city FROM customers WHERE city = 'Seattle';"
-t hides column headers, -A left-aligns output, and -F '|' sets the delimiter. The result is a plain pipe-separated block that jq or simple shell scripts can parse:
psql ... | while IFS='|' read -r id name city; do echo "{id: $id, name: \"$name\", city: \"$city\}"; done
For CSV export, replace -F ',' and add -R 0 to avoid row count footers:
psql -U app_user -d production_db -t -A -F ',' -R 0 -c "COPY (SELECT id, name FROM customers) TO STDOUT WITH CSV HEADER"
Pipe the output directly into a curl --data-binary @- POST if you need to forward results to another service.
Unescaped single quotes in user input are the most frequent silent failure mode. A question like “show me O'Brien’s orders” generates WHERE name = 'O'Brien's', which PostgreSQL rejects with:
ERROR: missing closing quote for character string at position 1
Always sanitize or escape user tokens before they enter the prompt, or use PostgreSQL’s parameterized query pattern (bind variables) when the LLM output is parsed and executed by application code rather than passed raw to psql -c.
temperature vs. top_p confusion. Setting temperature: 0 does not guarantee deterministic output if top_p is also low; some providers interpret the combination differently. For reproducible SQL generation, fix temperature: 0 and set top_p: 1.0, or use a provider-specific “deterministic mode” if available. Do not assume that temperature: 0 alone prevents the LLM from choosing among syntactically valid queries that differ in join order or alias naming.
Schema drift goes unnoticed until a query breaks in production. If a new column is added to a table or a table is renamed, the stored schema fragment becomes stale. The LLM will generate queries referencing the old identifier, and the error will surface as ERROR: relation "old_table_name" does not exist. Regenerate the schema fragment on a scheduled cadence—weekly for stable schemas, daily for actively evolving ones—and version the fragment alongside the prompt template.
Query result set size. An LLM may generate SELECT * against a table with millions of rows, causing the psql invocation to either timeout or return a result set too large for the downstream consumer. Insert a preflight LIMIT clause into the user prompt: “Return at most 100 rows.” Alternatively, wrap the LLM-generated query in an outer query that applies a limit, but be aware that this changes the semantics if the user intended aggregation or sorting.
Identifier case sensitivity. PostgreSQL folds unquoted identifiers to lowercase by default. If the LLM outputs SELECT * FROM Customers, the server resolves it as customers; if it outputs SELECT * FROM "Customers" with double quotes, it looks for an exact case match. Inconsistent quoting in generated SQL leads to “relation not found” errors that are easy to miss during testing. Enforce a system prompt rule: “Do not quote identifiers unless the name contains a space or mixed case.”
This page was rewritten on 14 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy