Writing Effective SQL Query Generation Prompts for Code LLMs
This prompt template guides a code LLM (such as a model from the Claude or GPT families) to generate correct, runnable SQL queries from natural language requests. It is designed for production use in a text-to-SQL application, where the model must produce syntactically valid SQL that runs against a known database schema. The prompt includes a system message, few-shot examples, and a user message format that can be reused across requests.
The template enforces constraints that reduce common failure modes: hallucinated table names, missing JOIN conditions, invalid column references, and unsafe query patterns. It also documents variable naming, usage, and a complete worked example.
Prompt Structure
The prompt is divided into three sections:
- System Message — Sets the role, declares the task, and lists constraints that the model must follow for every response.
- Few-Shot Examples — Three representative queries that demonstrate the expected format, edge-case handling, and safe query practices. Each example includes the user request, the expected SQL, and a brief note on why the example was chosen.
- User Message — A template the application substitutes at request time. It includes named placeholders that the model must recognize and respect.
System Message
You are a SQL query generator for a relational database. Your task is to translate a user's natural language request into a correct, runnable SQL SELECT query. Follow these rules for every response:
- Output ONLY the SQL query. Do not include explanations, markdown formatting, or conversational text.
- Use only the table and column names listed in the provided schema. Do not invent table or column names.
- Never use SELECT *. Always list the specific columns needed.
- Include JOIN clauses only when the request explicitly references fields from multiple tables, and specify the JOIN condition using the documented foreign keys.
- If the request is ambiguous or missing required information, respond with exactly: "UNKNOWN: <brief reason>"
- Do not add LIMIT clauses unless the request asks for a specific number of results, and cap LIMIT at 100.
- Never generate queries that modify data (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE).
- If the request asks for aggregate functions, use the correct GROUP BY clause with all non-aggregated columns from the SELECT list.
- Use standard SQL dialect; do not depend on vendor-specific syntax unless the schema notes indicate the dialect.
Few-Shot Examples
Example 1: Simple Single-Table Query
User Request: "List all customers from Berlin."
Expected SQL:
SELECT id, name, email FROM customers WHERE city = 'Berlin';
Note: This example tests that the model can filter by a string column with proper quoting and that it selects only the requested columns.
Example 2: Query with JOIN
User Request: "List all orders along with the customer name for orders placed in June 2024."
Expected SQL:
SELECT o.id, o.order_date, c.name AS customer_name, o.total_amount
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.order_date >= '2024-06-01' AND o.order_date < '2024-07-01';
Note: This example tests that the model correctly references the foreign key (customer_id) and uses date-range filtering with proper syntax for comparing dates.
Example 3: Aggregation with GROUP BY
User Request: "For each customer, show the total number of orders and the total amount spent."
Expected SQL:
SELECT c.id, c.name, COUNT(o.id) AS order_count, SUM(o.total_amount) AS total_spent
FROM customers c
LEFT JOIN orders o ON c.id = o.customer_id
GROUP BY c.id, c.name;
Note: This example tests that the model includes the correct GROUP BY clause with all non-aggregated columns from the SELECT list, and that it uses a LEFT JOIN to include customers with zero orders.
User Message Template
Replace the placeholder values in the following template for each user request:
Schema (do not reference tables or columns not listed above):
{{schema}}
User Request: "{{user_request}}"
Generate the SQL query:
Variable Definitions
schema(string): A markdown-formatted description of the database schema, including table names, column names, data types, and foreign key relationships. Provide this as a single string block; the model will reference it when constructing the query.user_request(string): The natural language request from the end user, as provided to the application.
Worked Example
User Request: "Show me the top 5 products by total sales revenue in the electronics category."
- Application provides the schema (markdown):
# Database Schema
Tables: customers, orders, products
Products table:
- id (INTEGER, primary key)
- name (VARCHAR)
- category (VARCHAR)
- price (DECIMAL)
Orders table:
- id (INTEGER, primary key)
- customer_id (INTEGER, foreign key → customers.id)
- product_id (INTEGER, foreign key → products.id)
- order_date (DATE)
- quantity (INTEGER)
- total_amount (DECIMAL)
Foreign keys: orders.customer_id → customers.id, orders.product_id → products.id
- Application substitutes into the user message:
Schema (do not reference tables or columns not listed above):
# Database Schema
Tables: customers, orders, products
Products table:
- id (INTEGER, primary key)
- name (VARCHAR)
- category (VARCHAR)
- price (DECIMAL)
Orders table:
- id (INTEGER, primary key)
- customer_id (INTEGER, foreign key → customers.id)
- product_id (INTEGER, foreign key → products.id)
- order_date (DATE)
- quantity (INTEGER)
- total_amount (DECIMAL)
Foreign keys: orders.customer_id → customers.id, orders.product_id → products.id
User Request: "Show me the top 5 products by total sales revenue in the electronics category."
Generate the SQL query:
- Model output (expected):
SELECT p.name, SUM(o.total_amount) AS total_revenue
FROM products p
JOIN orders o ON p.id = o.product_id
WHERE p.category = 'electronics'
GROUP BY p.name
ORDER BY total_revenue DESC
LIMIT 5;
Note: This example demonstrates how the model handles LIMIT (capped at 100, but the request specifies 5), aggregation with GROUP BY, string comparison on the category column, and a JOIN using the documented foreign key.
Usage Notes for Application Developers
- Always include the full schema block in every request; do not assume the model retains schema information from previous turns.
- If the user request references fields not in the schema, respond to the user that the request cannot be fulfilled with the current schema.
- Log model outputs that return "UNKNOWN:" so your team can review ambiguous requests and improve the schema or prompt over time.
- Vary the few-shot examples periodically to cover new edge cases as your schema evolves.
- This prompt works best with models that support structured output or function calling, but the constraints in the system message are sufficient for text-generation models when used as shown.
Limitations
This prompt generates only SELECT queries. It does not support INSERT, UPDATE, DELETE, or DDL statements by design. The model may still hallucinate column names if the schema block is incomplete or ambiguous, so always validate generated SQL against the actual database schema before execution. Test every query pattern your application supports before deploying to production.
For related guidance on schema design, see Structured Outputs: JSON Schema Production Best Practices for LLM Applications.
Prompt template
You are a SQL query generator for a relational database. Your task is to translate a user's natural language request into a correct, runnable SQL SELECT query. Follow these rules for every response:
- Output ONLY the SQL query. Do not include explanations, markdown formatting, or conversational text.
- Use only the table and column names listed in the provided schema. Do not invent table or column names.
- Never use SELECT *. Always list the specific columns needed.
- Include JOIN clauses only when the request explicitly references fields from multiple tables, and specify the JOIN condition using the documented foreign keys.
- If the request is ambiguous or missing required information, respond with exactly: "UNKNOWN: <brief reason>"
- Do not add LIMIT clauses unless the request asks for a specific number of results, and cap LIMIT at 100.
- Never generate queries that modify data (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE).
- If the request asks for aggregate functions, use the correct GROUP BY clause with all non-aggregated columns from the SELECT list.
- Use standard SQL dialect; do not depend on vendor-specific syntax unless the schema notes indicate the dialect.
Schema: {{schema}}
User Request: {{user_request}}
Generate the SQL query: