Back to cookbook

ChatGPT Prompt to Convert Plain English Questions Into SQL Queries

10 views Published

Make this prompt yours

Share

This ChatGPT prompt converts a plain English question into a working SQL query, so analysts, product managers, and developers who don't write SQL daily can still pull the data they need without waiting on an engineer. Instead of guessing at joins and syntax, you describe what you want to know and hand the model your table structure.

The key to getting a usable query back is giving the model your actual schema (table names, column names, and relevant data types) plus the SQL dialect you're running, since LIMIT and TOP syntax, date functions, and quoting rules all differ between Postgres, MySQL, and SQL Server. Without that context, the model will invent column names that look plausible but don't exist in your database.

For recurring reporting questions, it's worth saving a reusable version of this prompt rather than rewriting the schema block every time. If your schema description is long and you're sending it repeatedly across many queries, running it through the Prompt Optimizer's Coding mode first can tighten the wording without losing the structural detail the model needs to generate accurate joins.

Prompt template

Make this prompt yours

prompt-template
196 tokens
Role: You are a SQL expert helping me write a query for [DATABASE SYSTEM, e.g. PostgreSQL 15]. Context: - Here is my table schema: [PASTE TABLE NAMES, COLUMNS, AND DATA TYPES] - Relationships between tables: [DESCRIBE FOREIGN KEYS / JOIN LOGIC] Task: Write a SQL query that answers this question: [PLAIN ENGLISH QUESTION, e.g. "which customers placed more than 3 orders in the last 30 days"] Constraints: - Use only the tables and columns listed above - Add a short comment above each major clause explaining what it does - If the question is ambiguous, state your assumption in a comment at the top of the query - Return results sorted by [SORT FIELD] in [ASCENDING/DESCENDING] order Output format: Return only the SQL query in a code block, followed by a 2-3 sentence plain-English explanation of what it returns.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
176 tokens
Role: You are a SQL expert helping me write a query for PostgreSQL 15. Context: - Tables: customers(id, name, signup_date, country), orders(id, customer_id, order_date, total_amount) - Relationship: orders.customer_id references customers.id Task: Write a SQL query that answers this question: which customers from Canada placed more than 2 orders in the last 30 days, and what did they spend in total? Constraints: - Use only the tables and columns listed above - Add a short comment above each major clause explaining what it does - If the question is ambiguous, state your assumption in a comment at the top of the query - Return results sorted by total spend, descending Output format: Return only the SQL query in a code block, followed by a 2-3 sentence plain-English explanation of what it returns.

When to use it

  • You know what business question you're asking but not the exact SQL syntax to answer it
  • You're onboarding onto a new database and don't know the table relationships yet
  • You need a quick one-off query and don't want to open a separate SQL reference
  • You want a second version of a query you wrote by hand, to check for a simpler join or filter

Best practices

  • Paste the actual CREATE TABLE statements or column lists, not a vague description of what the tables contain
  • Name the SQL dialect explicitly (PostgreSQL, MySQL, SQL Server, BigQuery) since date and string functions differ
  • Ask the model to explain each join and filter in a comment above the relevant line, so you can verify the logic before running it
  • If you're pasting a large schema into every query prompt, compress the repeated boilerplate first with the Token Optimizer to cut the token cost without losing column names

Common mistakes

  • Asking for a query without sharing the schema, which leads the model to invent table or column names
  • Not specifying whether you want aggregated results, so the model guesses at GROUP BY logic
  • Running a generated query directly against a production database without checking it against a read replica or LIMIT clause first
  • Forgetting to mention existing indexes, which can lead to a correct but needlessly slow query on large tables

FAQs

Can ChatGPT write accurate SQL without seeing my actual database?

No. Without your real table and column names, the model will produce syntactically correct SQL that references fields that don't exist. Always paste your actual schema, even a simplified version, before asking for a query.

Which AI model is best for generating SQL queries?

ChatGPT, Claude, and Gemini can all generate SQL reliably when given clear schema context; the main differences show up on complex multi-table joins or less common SQL dialects, where double-checking the output against your database matters more than which model you used.

How do I get the AI to use the correct SQL dialect for my database?

State the dialect by name and version in your prompt, such as "PostgreSQL 15" or "BigQuery Standard SQL." Generic requests default to a common ANSI SQL style that may not support dialect-specific functions like window functions or date arithmetic.

Which Cuelara tool can help me tighten this SQL prompt before I reuse it?

Prompt Optimizer — its Coding mode is built for exactly this kind of structured, technical prompt and can restructure a messy schema-plus-question prompt into something cleaner to reuse. Intelligence Score — run your filled-in version through it to catch missing constraints, like an unspecified sort order or dialect, before you send it.

Found this prompt useful? Share it.

Share

More in Data Analysis

Data Analysis

AI Prompt to Perform Root Cause Analysis on a Sudden Metric Drop

This root cause analysis prompt helps analysts, product managers, and founders figure out why a key metric — signups, conversion rate, reven…

ROLE: You are a data analyst helping investigate a sudden change in a business metric.

CONTEXT:
- Metric: [METRIC NAME, e.g. "trial-to-paid conversion rate"]
- Normal value: [BASELINE VALUE OR RANGE]
- New value: [CURRENT VALUE]
- Time window of the drop: [START DATE] to [END DATE]
- Relevant data available: [PASTE NUMBERS, A TABLE, OR DESCRIBE THE CHARTS YOU HAVE]
- Known changes around this time: [LIST ANY DEPLOYS, CAMPAIGNS, PRICING CHANGES, OR "none known"]
- Audience for this analysis: [e.g. "engineering team", "founder", "board update"]

TASK:
1. List the most plausible causes for this drop, ordered from most to least likely given the data provided.
2. For each cause, state what evidence in the data supports or weakens it.
3. For each cause, specify the exact additional data or check that would confirm or rule it out.
4. Flag if the drop could simply be normal variance, and explain what would show that.
5. End with a short, plain-language summary suitable for the stated audience.

CONSTRAINTS:
- Do not state a cause as confirmed unless the provided data directly supports it — use "likely," "possible," or "unconfirmed" language for anything else.
- Do not invent data points that were not provided.
- Keep the hypothesis list to a maximum of 5 items.

OUTPUT FORMAT:
A numbered list of hypotheses (most to least likely), each with: supporting/weakening evidence, and the next check to run. Followed by a short summary paragraph.

Make this prompt yours

Data Analysis

AI Prompt to Build a Data Dictionary From a Spreadsheet or Database Table

This data dictionary prompt asks ChatGPT, Claude, or Gemini to turn a raw spreadsheet or database table into a clear reference document: eve…

You are a data analyst creating a data dictionary for a dataset so other people can understand and use it correctly.

Context:
- Source: [e.g., spreadsheet export, PostgreSQL table, CSV file]
- Table or sheet name: [NAME]
- Audience: [e.g., BI analysts, a new engineer, external partner]

Data sample (paste column headers plus 10-20 real rows below):
[PASTE SAMPLE DATA HERE]

Task:
For each column in the sample, produce:
1. Column name as it appears in the source.
2. Inferred data type (string, integer, decimal, date, boolean, categorical, etc.).
3. A one-sentence description of what the column represents, based only on the sample data.
4. Notes on anything unusual: nulls, mixed formats, inconsistent units, likely key or foreign key, or values that look like placeholders.
5. A confidence level (High, Medium, Low) for how certain you are about the description.

Constraints:
- Do not state a description as certain if the sample doesn't clearly support it; use Medium or Low confidence instead.
- Call out any columns that look like duplicates of each other or likely primary/foreign keys in a separate summary section.
- Keep descriptions to one sentence each.

Output format:
A single Markdown table with columns: Column Name | Data Type | Description | Notes | Confidence, followed by a short 'Keys and Relationships' summary section.

Make this prompt yours

Data Analysis

AI Prompt to Query and Analyze Supabase Data via Supabase's MCP Server

This prompt is for teams running Claude or ChatGPT with Supabase's MCP server connected, so the model can read a live Postgres database dire…

You are a data analyst with read-only access to a Postgres database through an MCP database connection. Follow these rules for every request:

ROLE
- Act as a careful analyst who verifies before concluding.

CONTEXT
- Database: [DATABASE NAME]
- Relevant tables: [TABLE NAMES, e.g. users, subscriptions, events]
- Business question: [QUESTION, e.g. how many trial users converted to paid in the last 30 days]

CONSTRAINTS
- Only run read-only SELECT queries. Never run INSERT, UPDATE, DELETE, or DDL statements.
- Before answering, list the exact query or queries you plan to run and wait for confirmation if any query touches more than [ROW LIMIT] rows.
- If a referenced table or column does not exist, say so explicitly instead of guessing a substitute.
- Show a sample of up to 5 returned rows alongside any aggregate numbers.

OUTPUT FORMAT
1. Queries run (as SQL)
2. Row counts and sample data
3. Plain-language answer to the business question
4. Any caveats about data quality or missing values

Task: [SPECIFIC ANALYSIS REQUEST]

Make this prompt yours