Back to cookbook

ChatGPT Prompt to Convert Plain English Questions Into SQL Queries

2 views Updated
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

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.

Example input

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.

Example output

-- Assumption: "last 30 days" is measured from the current date
SELECT
c.id AS customer_id,
c.name,
COUNT(o.id) AS order_count,
SUM(o.total_amount) AS total_spent
FROM customers c
-- Join orders placed by each customer
JOIN orders o ON o.customer_id = c.id
-- Restrict to Canadian customers
WHERE c.country = 'Canada'
-- Only orders from the last 30 days
AND o.order_date >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY c.id, c.name
-- Keep only customers with more than 2 qualifying orders
HAVING COUNT(o.id) > 2
ORDER BY total_spent DESC;

This query finds every Canadian customer who placed more than 2 orders in the last 30 days, groups their orders to count and total them, and sorts the results from highest to lowest total spend.

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

JSON Data Extraction Pipeline

This prompt converts messy, unstructured text (emails, articles, transcripts) into a predictable JSON array that your code can parse without…

Extract the following fields from the text below: [FIELD 1, FIELD 2, FIELD 3, FIELD 4].

Output rules:
- Return strictly a JSON array of objects, one per entity found.
- Use exactly these keys: [key_1, key_2, key_3, key_4].
- If a value is missing or unclear, use null. Never guess.
- Do not wrap the output in markdown code fences.
- Do not add any explanation before or after the JSON.

Text:
"""
[PASTE TEXT]
"""
Data Analysis

AI Prompt to Clean and Standardize a Messy Spreadsheet Dataset

This is a data cleaning prompt for turning a messy spreadsheet or CSV export into a consistent, analysis ready dataset — built for analysts,…

ROLE: You are a data cleaning assistant helping standardize a spreadsheet dataset for analysis.

CONTEXT: Below is a sample of the dataset. Columns are: [LIST OF COLUMN NAMES]

[PASTE SAMPLE DATA HERE, INCLUDING KNOWN PROBLEM ROWS]

TASK:
1. Review each column and identify formatting inconsistencies (e.g. date formats, capitalization, whitespace, abbreviations, units)
2. Propose and apply a single standard format for each column: [SPECIFY TARGET FORMATS WHERE KNOWN, e.g. dates as YYYY-MM-DD]
3. Flag rows that look like duplicates or outliers, but do not delete them — mark them for my review instead
4. Do not alter these columns without flagging first: [COLUMNS REQUIRING REVIEW BEFORE CHANGES, e.g. customer name, ID numbers]

CONSTRAINTS:
- Preserve every original row unless I confirm a deletion
- Do not invent or infer missing values — leave them blank and flag them
- [ANY ADDITIONAL CONSTRAINT, e.g. keep a specific column's original casing]

OUTPUT FORMAT:
1. The cleaned dataset as a table
2. A change log listing each column, what inconsistency was found, and what standard was applied
3. A separate list of flagged rows (possible duplicates/outliers) with a one-line reason for each flag
Data Analysis

AI Prompt to Find and Remove Duplicate Records in a Dataset

This AI prompt helps you find and remove duplicate records in a dataset, including near duplicates that differ only in casing, spacing, abbr…

Role: You are a data quality analyst reviewing a dataset for duplicate records.

Context:
- Dataset: [PASTE DATASET OR DESCRIBE FILE AND COLUMNS]
- Matching key(s): [FIELDS THAT SHOULD BE TREATED AS THE PRIMARY MATCH, e.g. EMAIL AND LAST NAME]
- Secondary fields to consider for near-matches: [E.G. PHONE NUMBER, COMPANY NAME, ADDRESS]
- Known formatting inconsistencies: [E.G. SOME ENTRIES HAVE EXTRA SPACES, MIXED CASE, ABBREVIATIONS]

Task:
1. Identify rows that are exact duplicates on the matching key(s).
2. Identify rows that are likely duplicates despite minor formatting differences (case, spacing, abbreviation, punctuation).
3. For each duplicate group, recommend which row to keep based on: [RULE, e.g. MOST RECENT DATE, MOST COMPLETE RECORD].

Constraints:
- Do not delete or merge any rows yourself — only recommend.
- Do not treat records as duplicates solely because one field matches if other key fields clearly conflict.
- Flag anything uncertain as "possible duplicate" rather than guessing.

Output format:
A table with columns: Row ID(s) involved | Match type (exact / likely / possible) | Matching fields | Recommended row to keep | Reason.
After the table, list any rows you could not classify confidently and why.