How to Write SQL Queries with AI (Prompts That Work)
Learn how to write SQL with AI: the prompt format that works, a worked example, a checklist to catch wrong answers, and what never to paste into a chatbot.

How do you write SQL with AI?
Give the AI three things: your table structure (column names and types), the question you want answered in plain English, and the SQL dialect you use (PostgreSQL, MySQL, Snowflake, BigQuery, SQL Server). Ask for the query plus a plain-language explanation of what it does. Then verify the result against a number you already trust before you use it. The AI writes a fast first draft. You are still responsible for whether the answer is right.
That last part matters most. AI is good at SQL syntax and bad at knowing what your data means. This guide covers the prompt format, a worked example, the checks that catch silent errors, and what to keep out of a chatbot.
TL;DR
- Paste the schema, not just the question. Without table and column names, the AI invents them, and the query looks plausible but fails or returns the wrong thing.
- Name your SQL dialect every time. Date functions and string handling differ between PostgreSQL, MySQL, Snowflake, BigQuery and SQL Server.
- Ask the AI to explain the query and state its assumptions. Most wrong answers come from a guess about what a column means, and the explanation exposes it.
- Check the output against a number you already know. A query that runs without errors can still be wrong, especially after joins.
- Never paste real customer data or credentials. Table structure is usually enough, and your company's AI policy decides what is allowed.
- Use AI for more than writing. Explaining an inherited query, debugging an error, and converting between dialects are often the biggest time savers.
What does AI need to write a correct SQL query?
AI cannot see your database. It only knows what you tell it. A request like "show me churned customers last quarter" forces it to guess your table names, what "churned" means, and which date column counts. It will guess confidently, and the code will look fine.
Give it these four inputs:
- The schema. Table names, column names, data types, and how tables connect (which column is the key that joins them). A
CREATE TABLEstatement works. So does a simple list. - The business definitions. What "active", "churned", "resolved" or "revenue" means in your data. Include which date column to use and any statuses to exclude.
- The dialect. Say "PostgreSQL" or "Snowflake" explicitly.
- The output shape. Which columns you want, how they should be named, how to sort, and whether you want a row per customer, per month, or per team.
You can get the schema without exposing any data. Most tools let you copy table definitions, or you can ask your data team for the documentation. If your company has a data dictionary, paste the relevant part.
How do you write the prompt? (A template you can copy)
Use this structure. Fill in the brackets and paste it into your approved AI tool.
You are helping me write a SQL query.
Dialect: [PostgreSQL / MySQL / Snowflake / BigQuery / SQL Server]
Tables:
[Paste CREATE TABLE statements or a list like:
customers(customer_id, name, plan, created_at)
tickets(ticket_id, customer_id, created_at, resolved_at, priority, channel)]
Relationships:
[tickets.customer_id joins to customers.customer_id]
Definitions:
[e.g. "Resolved" means resolved_at is not null. Month is based on created_at.]
Question:
[Plain-English question, as specific as you can make it]
Output I want:
[Columns, grouping, sort order, row limit]
Rules:
- Only use the tables and columns listed above. If something you need is missing, ask me instead of guessing.
- Write read-only SELECT queries only.
- Use readable aliases and add short comments.
- After the query, explain in plain English what it does and list any assumptions you made.
The line "If something you need is missing, ask me instead of guessing" does real work. It changes the AI's default from inventing a column to asking a question. The "read-only" rule keeps DELETE and UPDATE statements out of your drafts.
What does a worked example look like?
Say you work in customer support operations. You want to know how many tickets were resolved last month for each customer plan, and how long resolution took.
The prompt (filled in):
Dialect: PostgreSQL
Tables:
customers(customer_id, name, plan, created_at)
tickets(ticket_id, customer_id, created_at, resolved_at, priority, channel)
Relationships:
tickets.customer_id joins to customers.customer_id
Definitions:
Resolved means resolved_at is not null.
"Last month" means the previous full calendar month, based on created_at.
Question:
For each customer plan, how many resolved tickets were there last month, and what was the average time to resolve in hours?
Output I want:
plan, tickets_resolved, avg_hours_to_resolve (rounded to 1 decimal), sorted by tickets_resolved descending.
Rules:
Only use the tables and columns listed. Ask if anything is missing. SELECT only. Explain the query and list assumptions after.
A typical response:
SELECT
c.plan,
COUNT(*) AS tickets_resolved,
ROUND(
AVG(EXTRACT(EPOCH FROM (t.resolved_at - t.created_at)) / 3600)::numeric,
1
) AS avg_hours_to_resolve
FROM tickets t
JOIN customers c
ON c.customer_id = t.customer_id
WHERE t.resolved_at IS NOT NULL
AND t.created_at >= date_trunc('month', CURRENT_DATE) - INTERVAL '1 month'
AND t.created_at < date_trunc('month', CURRENT_DATE)
GROUP BY c.plan
ORDER BY tickets_resolved DESC;
The explanation should say that the date filter picks tickets created from the first day of last month up to, but not including, the first day of this month. It should also say that time to resolve is the gap between created_at and resolved_at, converted to hours.
What you should notice: the query filters by when the ticket was created, as you specified. A ticket opened on the 29th and resolved on the 3rd counts in last month, not this one. If your team reports on when tickets were resolved, that is a different number. The AI followed your definition. Whether your definition matches how your team reports is your call. This is the type of assumption to confirm before the number goes in a slide.
How do you check that an AI-written query is right?
A query that returns rows is not a correct query. Run these checks, in this order.
- Read the explanation against your intent. If the AI's plain-English description doesn't match what you meant, stop there. Fix the prompt.
- Run it on a small slice. Add
LIMIT 20, or filter to one customer or one day. Look at actual rows and see whether they make sense. - Reconcile with a number you already know. Compare the total to a dashboard, a finance report, or a count you can do another way. If your tickets total 1,240 and the query says 1,870, something is off.
- Check joins for duplication. This is the most common silent error. If you join a table where one customer has many rows (orders, tickets, line items) and then sum or count something from another many-row table, rows multiply and totals inflate. Compare
COUNT(*)before and after the join. - Check NULLs.
NULLis not equal to anything, including anotherNULL. Filters likestatus <> 'closed'silently drop rows where status is empty. Ask yourself whether missing values should be in or out. - Check date boundaries. Off-by-one errors around month ends, time zones, and
BETWEENon timestamps are common.BETWEEN '2025-01-01' AND '2025-01-31'on a timestamp column drops everything after midnight on the 31st. - Check what is being counted.
COUNT(*)counts rows.COUNT(DISTINCT customer_id)counts customers. The AI may pick the wrong one if your question was ambiguous.
If you want a second opinion, paste the query into a fresh chat and ask: "Review this query for logic errors, join duplication, NULL handling and date boundary problems. Here is the schema." A second pass catches some issues, though it shares the same blind spots about your business.
What are the best things to ask AI to do with SQL?
Writing from scratch is one use. These often save more time.
Explain a query someone else wrote. Inherited queries with five joins and nested subqueries are hard to read.
Explain this query step by step in plain English, as if to a colleague who knows the business but not SQL. Point out any filters that could exclude data unexpectedly.
[paste query]
Debug an error. Paste the query, the exact error message, and the schema.
This PostgreSQL query returns the error below. Explain what is causing it, then give me the corrected query.
Error: [paste exact message]
Query: [paste]
Schema: [paste]
Convert between dialects. Moving a query from MySQL to Snowflake or BigQuery usually means rewriting date and string functions.
Convert this MySQL query to BigQuery SQL. List every function you changed and why.
Improve readability. Ask it to restructure a messy query into common table expressions (CTEs), named steps that make logic easy to follow, without changing results. Then run both versions and confirm they return identical output.
Speed up a slow query. Paste the query and, if you can, the query plan your database produces. Ask for suggestions, but treat them as ideas to test. The AI can't see your data volume or indexes unless you tell it, so its advice may not apply.
Learn as you go. If you are newer to SQL, ask "Why did you use a LEFT JOIN here instead of an INNER JOIN?" You'll learn faster from your own queries than from a generic tutorial.
Which prompts work for common business questions?
These patterns work across roles. Swap in your own tables.
| You want to know | Prompt addition that helps |
|---|---|
| Month-over-month change | "Return one row per month with the value, the previous month's value, and the percent change. Handle months with no data." |
| Top N per group | "Return the top 3 accounts by revenue within each region. Use a window function and explain it." |
| Customers with no activity | "Find customers with no tickets in the last 90 days. Use a LEFT JOIN and explain why." |
| Duplicates | "Find rows in this table that share the same email, and show how many each has." |
| Cohort or retention | "Group customers by signup month and show what share were still active 1, 3 and 6 months later. State how you defined active." |
| Funnel steps | "Count distinct users who reached each stage. Make sure each user is counted once per stage." |
For any of these, finish with "List your assumptions." The assumptions list is where you'll find the mismatch between what you meant and what the AI did.
Where should you not trust AI for SQL?
- Meaning. AI doesn't know that your
status = 3means "refunded" or thatamountis in cents. Tell it, or it will guess. - Large or sensitive changes. Never run an AI-written
UPDATE,DELETE,DROPorALTERagainst a production database without review by someone who owns that data, and ideally a backup and a test run first. - Performance at scale. A query can be correct and still take an hour or cost real money on a cloud warehouse that charges by data scanned. Ask your data team before running heavy queries on big tables.
- Numbers that go to executives, customers or regulators. These need a human who understands the definitions to sign off.
- Made-up functions. AI sometimes uses a function that doesn't exist in your dialect. If you get an "unknown function" error, tell it the dialect and the error and ask again.
What should you never paste into an AI tool?
Don't paste customer names, emails, phone numbers, payment details, health information, employee records, passwords, API keys or connection strings. You rarely need them. Table and column names are enough to get a good query, and made-up sample rows work for testing logic.
Also check your company's rules. Many large companies approve specific AI tools and prohibit others, and a schema can itself be confidential. If your company provides an approved assistant, use that one. If you are unsure, ask IT or security before pasting anything.
Can AI query the database for you directly?
Some tools connect an AI to a database so you can ask questions and get answers without seeing the SQL. This is convenient, but you lose the review step. If you can't read the query, you can't catch the wrong join or the wrong definition. Where possible, choose a setup that shows the SQL it ran, uses a read-only account, and limits access to the tables you are allowed to see. Access to company data is a decision for your data and security teams, not something to set up on your own.
What if you run the same query every week?
If you rerun the same query every Monday and paste the results into a spreadsheet or an email, the query is not the slow part anymore. The routine around it is. A small internal tool can take that over: a page that shows the numbers, filters by team or date, and refreshes on a schedule.
Remy is an AI product agent that builds full-stack business apps from a plain-English description, with a managed SQL database, sign-in and scheduled jobs included. You could describe a ticket-tracking dashboard or a weekly report page and have it built and deployed to a live URL. It suits tools that run on data you load into the app. Whether an app can reach your company's data warehouse is a question to settle with your IT and data teams first.
Frequently Asked Questions
Can ChatGPT or other AI tools write SQL?
Yes. General-purpose AI assistants write SQL well for common tasks like joins, grouping, filtering and window functions. The quality depends on the context you give. With your schema and definitions, results are usually close to usable. Without them, you get a plausible guess that needs rework.
Is AI-generated SQL accurate enough to trust?
Trust it as a draft, not as an answer. The syntax is usually fine. The errors tend to be logical: wrong date column, duplicated rows after a join, mishandled NULLs. Check results against a number you already know, and have someone review anything that feeds a decision or a report.
Do I need to know SQL to use AI for it?
You can get started without it, but learning to read basic SQL makes you much more effective. You need to be able to follow what the query filters, joins and counts, so you can spot when it doesn't match your question. Asking the AI to explain each part is a fast way to learn.
Will AI replace people who write SQL?
It changes the work more than it removes it. Drafting queries gets faster, so more of the job is knowing which question to ask, what the data actually means, and whether the result is right. Analysts and engineers who check and explain results are more useful, not less. People in support, success and operations can now answer more of their own questions, with review from the data team for anything important.
What is the best prompt to get SQL from AI?
Include your dialect, your tables and columns, how tables relate, your definitions, the exact output you want, and the instruction "ask me if anything is missing and list your assumptions." The template above covers all of it. Specific prompts beat clever ones.
How we source, write, and correct our articles. Editorial standards
Related articles

How to Analyze NPS and CSAT Survey Comments with AI

How to Present Data to Executives: A Step-by-Step Guide

GPT-6.2 Astra vs Gemini 4 Neon vs Claude Fable 5.2: Which to Use
