Claude API SQL Query Generation Tool: Build Guide
If you're searching for a "Claude API SQL query generation tool," you're probably trying to let users ask questions in plain English and get back working SQL — or you want to add a natural-language-to-SQL layer on top of an existing database without hand-rolling a parser. Claude is well suited to this because it handles schema context, joins, and edge cases (NULL handling, date arithmetic, aggregations) better than rule-based NL-to-SQL systems, and it can explain its reasoning when a query looks wrong.
This article walks through what actually works when building this kind of tool: how to structure prompts with schema context, how to validate generated SQL before it touches a database, and how to wire the whole thing into a production API using streaming and tool use.
Why Claude works well for SQL generation
Rule-based NL-to-SQL tools break on ambiguity: "top customers last quarter" requires knowing what "top" means (revenue? order count?), what "last quarter" resolves to in UTC, and which table holds customer status. Claude handles this because you can give it:
- The actual schema (table names, columns, types, foreign keys)
- Sample rows or column value distributions
- Business context ("status is 'active', 'churned', or 'trial'")
- Prior query history for follow-up questions
The model then generates SQL that's grounded in your real schema instead of guessing table names. The tradeoff is that you need a tight feedback loop — generation, validation, and execution — because an LLM will confidently write a query against a column that doesn't exist if your schema context is stale or incomplete.
Structuring the prompt
The core of this tool is the system prompt. Keep it narrow and explicit:
You are a SQL generator for a PostgreSQL database.
Only output a single SQL query, no explanation, no markdown fences.
Use only the tables and columns listed below. If the question
cannot be answered with these tables, output: ERROR: <reason>
Schema:
customers(id, name, email, created_at, status)
orders(id, customer_id, total_cents, created_at, status)
order_items(id, order_id, product_id, quantity, price_cents)
Rules:
- Always qualify columns with table aliases.
- Use created_at for date filtering, never updated_at.
- Monetary columns are in cents; divide by 100 only in the final SELECT.
This kind of constraint — "only output a single SQL query" plus an explicit error path — matters more than clever phrasing. Models are good at following hard rules when you state them directly.
Generic example
const response = await fetch("https://api.example-llm.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
},
body: JSON.stringify({
model: "claude-model-id",
system: SQL_SYSTEM_PROMPT,
messages: [
{ role: "user", content: "Show me customers who spent over $500 in the last 30 days" }
],
max_tokens: 400
})
});
The response should be a single query. If it starts with ERROR:, surface that to the user instead of trying to run it.
Validating generated SQL before execution
Never execute LLM-generated SQL directly against a production database. At minimum:
- Parse before you run it. Use a SQL parser (e.g.,
node-sql-parserorsqlglotin Python) to confirm it's a single, syntactically validSELECTstatement. Reject anything else outright. - Whitelist tables and columns. Cross-check parsed identifiers against your known schema. Reject queries touching tables not in the allowlist.
- Block write operations. Reject
INSERT,UPDATE,DELETE,DROP,ALTER, and multi-statement queries (;followed by more SQL). - Run against a read replica with a connection-level timeout and a row limit (
LIMIT 1000appended if missing). - Use a dedicated read-only DB role so even a validation gap can't cause damage.
This validation layer is non-negotiable — it's the difference between a demo and a tool you can put in front of real users.
Handling follow-up questions and tool use
Users rarely ask one-shot questions. "Now break that down by region" requires the model to remember the previous query's intent. Two approaches work:
- Conversation history: pass prior user/assistant turns so Claude has context on what "that" refers to.
- Tool use: define a
run_querytool that Claude calls with asqlargument, and your backend executes it and returns results as the tool result. This gives you a clean separation between "Claude decides what to query" and "your code decides whether to run it." See/docs/toolsfor how tool definitions and tool results are structured.
Tool use is the better pattern for production because it forces an explicit, inspectable boundary — you get the proposed SQL as structured input, not free text you have to extract from a longer response.
Streaming for long-running analysis
If your tool also explains the query results ("here's what this data shows"), streaming matters for perceived latency. Rather than waiting for the full explanation, stream tokens as they're generated so the UI feels responsive while the query itself runs in the background. Details on setting this up are in /docs/streaming.
Putting it behind a production API
Once the prompting and validation logic work, you need a reliable way to call Claude from your backend — with usage visibility, team access, and a stable key you're not managing directly against a provider console. This is where SubToAPI fits: it turns your existing Claude access into a standard HTTPS API with sub_live_... application keys, so your SQL generation service calls one consistent endpoint instead of juggling provider-specific auth.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet",
"system": "You are a SQL generator for a PostgreSQL database...",
"messages": [
{"role": "user", "content": "Show total revenue by product category this year"}
],
"max_tokens": 400
}'
For a team building this internally — a data platform group, an internal BI tool, an analytics feature inside a SaaS product — SubToAPI gives you per-key usage metadata so you can see which service or environment is generating queries, plus team seats if more than one engineer needs access to the underlying Claude account. Check /docs/quickstart to get a key running in minutes, and /pricing for the Solo, Team, and Scale plans.
FAQ
Can Claude generate SQL for any database dialect?
Yes, but you need to specify the dialect (PostgreSQL, MySQL, Snowflake, etc.) explicitly in the system prompt, since syntax for dates, string functions, and pagination differs across engines. Without that, Claude will default to whatever dialect is most common in its training data, which may not match yours.
Is it safe to let Claude-generated SQL run directly against production?
No. Always validate with a parser, whitelist tables/columns, block non-SELECT statements, and run queries against a read-only replica with a row limit and timeout. Treat the model's output as untrusted input, the same way you'd treat user-submitted form data.
How do I get an API key to start building this?
Sign up at /signup to get a SubToAPI key, then follow /docs/quickstart to send your first request. From there, /docs/messages and /docs/tools cover the message format and tool-calling patterns used in the examples above.