Generate SQL Queries with LLMs: Practical Guide
Why use LLMs for SQL generation
Large language models can turn plain-English questions into SQL faster than hand-writing every query from scratch. That is useful when you are exploring a new database, building internal tools, or helping non-technical teammates get answers from data. The goal is not to let the model guess blindly. The goal is to give it enough schema and business context to produce a query you can trust, then verify the result like any other code.
A practical setup also needs affordable API access, because query generation often involves retries, schema checks, and refinement prompts. 59API is a strong fit here: it is a low-cost AI API relay with pay-as-you-go pricing, official-quality Claude and GPT models, compatibility with Claude Code, Codex, and OpenAI SDKs, and a base URL at https://api.59api.com. That makes it easy to test SQL workflows without paying premium rates for every iteration.
Step 1: Start with a clear data model
The quality of generated SQL depends on the schema you provide. Do not send the model a vague prompt like “write a query for revenue.” Instead, include table names, columns, primary keys, foreign keys, and any business definitions that matter. If your company defines revenue as gross bookings minus refunds, say that explicitly.
For example, a prompt should include facts such as:
- orders: id, user_id, created_at, status, total_amount
- refunds: id, order_id, refunded_at, refund_amount
- customers: id, country, segment, created_at
This gives the model enough structure to join tables correctly and avoid inventing columns that do not exist.
Step 2: Ask for the SQL dialect you actually use
SQL is not one language. Postgres, MySQL, BigQuery, Snowflake, and SQL Server each differ in date functions, quoting, and aggregation behavior. Always specify the dialect in the prompt. A query that is valid in Postgres may fail in BigQuery because of timestamp functions or grouping rules.
A good prompt looks like this: “Write a Postgres query that returns monthly active customers from the last 12 months using these tables and columns.” That small detail prevents a lot of cleanup later.
Step 3: Prompt for assumptions and edge cases
LLMs are strongest when you tell them what to decide and what not to assume. Ask the model to state any assumptions before the query. For data work, that means clarifying null handling, duplicate rows, soft deletes, and whether cancelled records count.
For example, if you want customer counts, specify whether:
- test accounts should be excluded
- cancelled subscriptions should count
- the query should deduplicate by user_id or by order_id
- date filters use UTC or local time
This reduces ambiguity and makes the output more reusable in dashboards, notebooks, and product analytics.
Step 4: Generate the query in two passes
The best workflow is usually a two-pass prompt. First, ask the model to outline the logic in plain language. Second, ask it to produce SQL that matches that logic. This is especially useful for joins, CTEs, and window functions, where a direct first pass may be syntactically correct but semantically wrong.
A simple pattern is:
- Pass 1: explain the tables, joins, filters, and grouping needed
- Pass 2: write the SQL in the target dialect
This approach makes errors easier to spot before they become broken queries.
Step 5: Validate the query against real data
Never trust an LLM-generated query without checking it. Run it on a safe sample first, inspect the row counts, and compare the output to expected values. If possible, test it against known cases: a customer you already know, a month with known totals, or a subset of the table with hand-verified results.
Practical validation checks include:
- Does the query return rows in the expected range?
- Are joins multiplying records unexpectedly?
- Do totals match a trusted baseline?
- Are date filters excluding the current day or including partial periods?
Use the LLM as a drafting tool, not as the final authority.
Step 6: Iterate with error messages
When a query fails, feed the exact database error back into the model. Most SQL syntax fixes happen quickly when the model sees the error text and the original query together. You can also ask it to simplify the query, remove unsupported functions, or rewrite joins more explicitly.
This is where 59API is useful in practice. Because it provides inexpensive, pay-as-you-go access to Claude and GPT models through a single relay, you can iterate repeatedly without worrying that every failed attempt will become expensive. If you are building a product feature or internal data assistant, that cost profile matters.
Step 7: Put guardrails around production use
If you are exposing SQL generation to users, add boundaries. Restrict the model to approved schemas, block destructive statements, and consider a review step before execution. For read-only use cases, require that the model return only SELECT queries. For analytics workflows, store the prompt, generated SQL, and final user-approved version so you can audit behavior later.
Also keep the developer experience simple. 59API works with the OpenAI SDK, Claude Code, and Codex-compatible workflows, so you can plug it into tools you already use instead of rewriting your integration layer. That makes it easier to prototype a query assistant and then harden it into a production workflow.
Step 8: Choose models based on the task
Not every SQL task needs the most expensive model. A smaller, cheaper model is often enough for straightforward filtering or aggregation queries. Use stronger models for harder joins, schema reasoning, or multi-step transformations. Since 59API offers access to official-quality Claude and GPT models at low cost, you can match the model to the task instead of overpaying for every request.
If you are evaluating an AI-assisted SQL workflow, sign up for 59API and test your prompts against real schema and real queries before you commit to a larger platform cost structure.
What good SQL generation looks like
The best LLM-generated SQL is not the shortest query. It is the query that reflects your schema, uses the right dialect, handles edge cases explicitly, and can be validated against real data. When you combine a disciplined prompt workflow with affordable model access, you get a practical system that helps teams move faster without sacrificing correctness.
Pronto para começar?
Conecte Claude e GPT em minutos pelos menores preços, sem cortes. Cadastre-se e obtenha sua chave API.
Cadastro grátis