ChatGPT Prompt to Generate SQL Queries from Plain English
The Scenario
You need a report from your database but you do not remember the exact JOIN syntax, or the schema is a tangle of tables you did not design. Typing a question in English and getting back a working, safe SQL query is one of the highest-leverage things ChatGPT can do for non-experts. The catch: a vague prompt produces a query that looks right and silently returns the wrong rows, or worse, one that tries to DROP a table. This prompt fixes that by forcing you to supply the schema, the exact question, and guardrails against destructive or unsafe SQL, plus a clear explanation of what the result means.
The biggest risk with AI-written SQL is confidence without correctness. A generated query that runs without error but returns the wrong rows is more dangerous than one that fails loudly. The prompt below trades a little extra setup (pasting your schema) for a much higher chance the query is both valid and correct. Spend two minutes on the schema line and save two hours of debugging.
The Copy-Paste Prompt
Fill the schema and the question, then paste into ChatGPT. Keep the guardrails section; it is what stops the model from inventing tables.
You are a senior SQL engineer. Write a query for the database described below.
Dialect: {{DIALECT}}
Schema:
{{SCHEMA}}
Request: {{REQUEST}}
Rules:
1. Use ONLY tables and columns listed in the schema. Do not invent names.
2. Prefer explicit JOINs over comma joins.
3. Add a LIMIT 100 unless the user asks for all rows.
4. Do NOT write UPDATE, DELETE, DROP, or INSERT. Read-only SELECT only.
5. If the request cannot be answered from the schema, say so and explain what is missing.
6. After the query, add a one-line comment explaining what it returns.
Variables You Must Fill
| Variable | What to put | Example |
|---|---|---|
| {{DIALECT}} | Database engine | PostgreSQL 15 / MySQL 8 / SQLite |
| {{SCHEMA}} | Table and column definitions | users(id, name, created_at); orders(id, user_id, total, status) |
| {{REQUEST}} | Plain-English ask | Top 10 users by total spend in completed orders this year |
The {{SCHEMA}} line is the difference between a useful query and a hallucinated one. Paste it straight from your DESCRIBE or \d output; do not summarize from memory. If a table name is ambiguous (say, two “status” columns in different tables), spell out the fully qualified names in the schema so the model does not guess. The {{DIALECT}} matters too: date functions, string concatenation, and LIMIT syntax differ across engines.
Expected Output
SELECT u.name, SUM(o.total) AS spend
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE o.status = 'completed'
AND o.created_at >= DATE_TRUNC('year', CURRENT_DATE)
GROUP BY u.name
ORDER BY spend DESC
LIMIT 10;
-- Returns the 10 highest-spending users from completed orders this year.
You get a read-only query that matches your real schema and a comment confirming intent. Because rule 4 blocks writes, you can run it in a test console without fear. If the model says “this cannot be answered from the schema,” trust it: you are probably missing a join table or a column, and the honest refusal saves you from a wrong result.
Why This Prompt Works
The schema is the anchor. Without it, the model draws on generic training examples and invents plausible column names like “order_date” when yours is “created_at,” producing a query that errors or, worse, runs against the wrong column. Rule 1 turns that temptation off. The read-only guardrail (rule 4) is a deliberate safety choice: even if you later want a write, starting read-only lets you confirm the SELECT returns sane rows before touching data. The trailing comment enforces a one-line sanity check you can read at a glance.
Common Mistakes to Avoid
- Vague requests: “show me the data” gives a generic dump. Name the metric, filter, and sort explicitly.
- Wrong dialect: asking for MySQL date math on a PostgreSQL schema yields errors. Match
{{DIALECT}}exactly. - Trusting the row count: always eyeball the result size. A query that returns 0 or 10 million rows usually means a join or filter is off.
- Skipping the LIMIT: on big tables an unbounded query can lock resources. The prompt adds LIMIT 100 by default for safety.
Variation Tips
- Explain mode: add “Also explain the query line by line for a beginner” to learn as you go.
- Edge cases: append “Handle NULL totals as 0 and exclude test accounts (email like ‘%@test’)” to harden the result.
- Multiple dialects: ask “Now give the MySQL 8 version of the same query” to port it.
- Safety toggle: for admins who do need writes, replace rule 4 with “Wrap any write in a transaction and add a SELECT count before it” so you can preview impact.
- Window functions: add “Use a window function for running totals” when you need cumulative metrics.
Before trusting generated SQL in production, pair this with a debugging workflow from How to Debug Code with ChatGPT and compare vague vs specific asks in Vague vs Specific Coding Prompts. For the model settings that make these queries cleaner, see ChatGPT Coding Settings.
Quick Checklist Before You Run It
- Did you paste the real schema, copied from the database, not paraphrased from memory? Guessed column names cause silent wrong results.
- Does the dialect match your engine? Date and string functions differ across PostgreSQL, MySQL, and SQLite.
- Is the query read-only? Rule 4 should still be intact unless you deliberately changed it for an admin task.
- Does the trailing comment describe what you expected? If not, the query may be answering a different question.
- Will you run it on staging first? Never point AI-generated SQL at production data without a test pass.
Generated SQL is a suggestion from a very confident assistant, not a verified report. The schema anchor and the read-only guardrail make it safe to experiment, but the final responsibility for correctness stays with you.
Sources & Notes
Prompt written for ChatGPT GPT-4o and later; SQL generation is a well-supported capability as of 2024-2025. The read-only guardrail (rule 4) is a deliberate safety choice, not a model limitation. Always run generated queries on a staging or read-replica first, and confirm row counts look sane. No live database was connected; schema and output examples are illustrative. Validate against your actual DBMS dialect before use. AI-generated SQL should be reviewed by a human before touching production data.
