Claude Prompts for Writing SQL Queries (2026)
To get correct SQL from Claude, give it your table shape first, then ask for one query at a time. Paste your CREATE TABLE statements (or a few sample rows), name your dialect — Postgres, MySQL, or SQLite — and ask Claude to explain each query, not just produce it. Below are 13 copy-ready prompts for joins, aggregations, window functions, debugging, and dialect translation. One rule never bends: read the query and test it on a copy before you run it on production.
LIMIT inside a
transaction you can roll back, and confirm the row counts look right before you trust it.
Start here — give Claude your schema (prompts 1–2)
This is the step most people skip, and it's why they get queries full of made-up columns. Load your table shape once at the top of the conversation and every prompt after it gets sharper.
I'm going to give you my database schema. Here are the CREATE TABLE statements for the tables involved: [PASTE CREATE TABLE STATEMENTS]. From now on, write queries using only these exact table and column names. If a query would need a column that isn't listed here, stop and tell me instead of guessing. My database is [Postgres 16 / MySQL 8 / SQLite].
I don't have the CREATE TABLE statements handy. Here are three sample rows from each table as CSV, plus a one-line description of what each table holds: [PASTE]. Infer the columns, data types, and likely primary and foreign keys, then list what you inferred so I can correct you. Don't write any query until I confirm.
Joins and filtering (prompts 3–5)
Joins are where beginners get silently wrong answers. Ask Claude to name the join it used and why, so you learn the pattern instead of just copying output.
Using the schema above, write a query that returns each customer's name alongside their most recent order date. Customers with no orders should still appear, with a NULL order date. Tell me which join type you used and one sentence on why it's the right one here.
Write a Postgres query for all orders from the last 30 days with a status of 'shipped' or 'delivered', for customers in Florida. Use a parameter placeholder for the date cutoff instead of hardcoding it, and add a one-line comment above each part of the WHERE clause explaining what it filters.
I have students, courses, and an enrollments join table. I want every student enrolled in 'Biology' but NOT in 'Chemistry'. Show me two versions — one using NOT EXISTS and one using LEFT JOIN ... WHERE ... IS NULL — and tell me which is usually faster and why.
Aggregations and window functions (prompts 6–8)
This is the leap from "list the rows" to "answer the question." Have Claude show the result columns it expects so you can sanity-check the totals against rows you already know.
Write a query giving total revenue and order count per month for 2025, sorted newest month first. Revenue is orders.amount. Use date_trunc('month', order_date) for the grouping (Postgres). List the exact result columns you expect so I can verify them against a few known rows.
Teach me window functions with my own data. Write a query that finds the top 3 best-selling products within each category, using ROW_NUMBER() OVER (PARTITION BY category ORDER BY total_sold DESC). Put a one-sentence comment above the window clause explaining what PARTITION BY and ORDER BY are each doing.
I want a running total of daily revenue for the year: each row should show that day's revenue and the cumulative total up to that day. Use SUM(daily_revenue) OVER (ORDER BY day). Then explain in two sentences why this needs a window function and can't be done with GROUP BY.
Debugging errors and wrong results (prompts 9–11)
Claude is at its best on the queries that broke. Give it the exact error text and the query — not a paraphrase — and ask for the smallest fix so you learn the cause instead of blindly swapping in a rewrite.
This query throws the following error: [PASTE THE EXACT ERROR MESSAGE]. Here's the query: [PASTE QUERY], and my schema is above. Explain in plain English what the error actually means, the root cause, and the smallest change that fixes it. Don't rewrite the whole query unless you truly have to.
This query runs but the totals are way too high — I think a join is multiplying rows. Here's the query and schema: [PASTE]. Walk me through what each join could fan out, give me a small diagnostic query to count rows before and after each join, and then show the fix (a pre-aggregation, DISTINCT, or a different join key).
This query is slow on a table with about 5 million rows: [PASTE QUERY]. In order, tell me: what's most likely expensive, which indexes would help, and how to read the EXPLAIN output. Give me the CREATE INDEX statements, but explain the write-speed and storage tradeoffs before I add them.
Translating between SQL dialects (prompts 12–13)
Postgres, MySQL, and SQLite look identical and then bite you on the other 10% — date functions, string aggregation, case sensitivity. Ask Claude to teach the differences, not just hand you three files.
Translate this Postgres query to MySQL 8 and to SQLite: [PASTE QUERY]. Call out every function or bit of syntax that differs across the three — things like date_trunc, ILIKE, string_agg vs group_concat, and LIMIT/OFFSET — and give me a one-line note on each change so I understand it, not just three finished versions.
I'm on SQLite, which has no native date type. Show me the correct way to store and compare dates as ISO-8601 text, rewrite this Postgres date query for SQLite: [PASTE], and warn me about the two mistakes people most often make with SQLite dates.
Go from copy-pasting prompts to actually understanding SQL
Our self-paced course teaches the exact workflow behind these prompts — loading context, scoping the task, and using Claude as a tutor that explains every query — with hands-on lessons you can follow at your own pace. One-time payment, lifetime access.
Get instant access → $49.99How to get better results
The difference between a query that works and one that quietly returns wrong numbers is almost always in how you asked. Five habits do most of the work:
- Give the schema first. CREATE TABLE statements are best; sample rows are a fine fallback. This one step eliminates most hallucinated column names.
- Name the dialect and version. "Postgres 16," "MySQL 8," "SQLite" — the syntax genuinely differs, and Claude can't pick correctly if you don't say.
- Ask it to explain, not just produce. "Explain each part of the WHERE clause" turns every answer into a lesson and helps you catch mistakes.
- Provide expected output. Tell Claude what the result columns should look like; it will work backward to a query that hits your target.
- Iterate in steps. For anything complex, ask for the approach first, confirm it, then ask for the SQL — the same two-step pattern behind our resume and job-search prompts.
Mistakes to avoid
- Running unread SQL on production. The big one. Read it, test it on a copy, and never let an AI-written UPDATE or DELETE hit real data without confirming the WHERE clause yourself.
- Skipping the schema. Without it, Claude invents plausible column names that don't exist — errors a 30-second paste would have prevented.
- Trusting numbers you didn't spot-check. A query can run cleanly and still be wrong. Verify totals against a few rows you already know.
- Ignoring NULLs. NULLs change how joins, COUNT, and AVG behave. If a result looks off, ask Claude how NULLs are affecting it.
- Not naming the dialect. A query that works in Postgres may behave differently in MySQL or SQLite. State your database every time.
- Blindly adding indexes. Indexes speed reads but slow writes and use storage. Ask for the tradeoff first.
New to Claude entirely? Start with our 10-minute guide to installing Claude AI, then work through these prompts against a throwaway copy of your database. For more copy-ready recipes, browse the full Learn hub.
Want the query without writing the prompt? Try the SQL Query Builder skill
Skillforge AI includes a pre-built SQL Query Builder skill: paste your schema and describe what you want in plain English, and it returns a correct, explained query in your dialect — joins, aggregations, window functions, and dialect translations handled for you. Try it free for 7 days, then $29.99/month. Cancel anytime.
Try the SQL Query Builder free →Frequently asked questions
Can Claude write SQL queries for me?
Yes. Claude writes joins, aggregations, window functions, and full reports well — but only when you give it your real table shape first. Without your schema it guesses column names, so paste your CREATE TABLE statements or a few sample rows before asking for a query. Always read the query and test it on a copy before running it on production.
Do I need to give Claude my database schema?
It's the single biggest factor in getting correct SQL. Paste your CREATE TABLE statements, or if you don't have them, paste three sample rows per table plus a one-line description of each. Then ask Claude to list the columns and keys it inferred so you can correct any wrong assumptions before it writes against invented column names.
Can Claude convert a query between Postgres, MySQL, and SQLite?
Yes, and it's one of the best uses for it. Paste the query, name the source and target dialect and version, and ask Claude to call out every function that differs — date_trunc, ILIKE, string_agg versus group_concat, LIMIT syntax, date handling. Ask for the explanation of each change, not just three finished versions, so you catch dialect traps yourself.
Is it safe to run SQL that Claude wrote on my production database?
Not without reading it first. The golden rule: read every line, then test on a copy, a staging database, or with a LIMIT inside a transaction you can roll back. Be especially careful with UPDATE and DELETE — an AI-written statement missing a WHERE clause will change every row. Run a SELECT version to preview which rows a write would touch before you run the write.
Is Claude or ChatGPT better for SQL?
Both write competent SQL. Claude tends to follow constraints faithfully — sticking to the exact column names you gave it, honoring dialect and length limits, and flagging when a query needs a column that doesn't exist rather than inventing one. It also handles long inputs like a full schema plus several sample tables in one conversation. Either way, the schema you provide matters more than the model.
About the authors
Ozz is a Miami-based private investigator and small-business owner who runs his legal-support practice, content channels, and finances with Claude in the loop daily — including the SQL behind his own reporting. Rob co-leads Claude AI Class from the prompting and tooling side, and has been building with Claude since the model's first public release. Together they teach a hands-on, self-paced beginner course.
